New in Symfony 4.2: Wait until processes are ready

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

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:

use Symfony\Component\Process\Process;

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

// wait a few seconds for the process to be ready

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:

$process->waitUntil(function ($type, $output) {
    return $output === 'Ready. Waiting for commands...';
Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

New in Symfony 4.2: Wait until processes are ready

Tweet this


Awesome stuff! :) Thanks a lot!
Nice. Thanks :)
That’s handy; Thanks!

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.