New in Symfony 4.2: Wait until processes are ready

Contributed by
Maxime Veber
in #27742.

The Symfony Process component executes commands taking care of the differences between operating system and escaping arguments to prevent security issues. One of the features it provides is the wait() method, which blocks the app execution until the given process has finished.

However, for some kinds of commands (such as long running processes) you can't use this method because the process never ends. That's why it's common to find code like this, which waits a few seconds for the process to start:

1
2
3
4
5
6
7
use Symfony\Component\Process\Process;

$process = new Process(['/usr/bin/php', 'slow-starting-server.php']);
$process->start();

// wait a few seconds for the process to be ready
sleep(3);

However, this code is fragile because the process may take longer to be ready than the given time. In Symfony 4.2 we've added a new waitUntil() method which receives a callback as argument and keeps waiting until the callback returns true.

The callback is called repeatedly whilst the process is still running, passing in the process output and its type (Process::ERR or Process::OUT) as its arguments.

In the above example, instead of waiting a fixed number of seconds, you could wait until some text is printed in the console showing that the process is ready:

1
2
3
$process->waitUntil(function ($type, $output) {
    return $output === 'Ready. Waiting for commands...';
});

Comments

Awesome stuff! :) Thanks a lot!
Nice. Thanks :)
Great.....
That’s handy; Thanks!
Login with SymfonyConnect to post a comment