symfony

Maxime Veber shared today a very interesting feature in Symfony 4.2 to let your code wait for a process to finish before running another. 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.

This kind of code is very fragile because we don’t know if the process needs two or three seconds to finish, or maybe more.

That’s why in symfony 4.2 there is 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) 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...'; });

LEAVE A REPLY

Please enter your comment!
Please enter your name here