Running a background task using Symfony Process without having to wait for the process to finish

Running Processes Asynchronously

You can also start the subprocess and then let it run asynchronously, retrieving output and the status in your main process whenever you need it. Use the start() method to start an asynchronous process

documentation

so, to start your command asynchronously you should create new process with command and start it

$process = new Process('php bin/console hello:word');
$process->start();

Consider to change this to full paths like \usr\bin\php \var\www\html\bin\console hello:word

Also there is good bundle cocur/background-process you may use it, or at least read the docs to find out how it works.


For using in controller:

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;

$myVar = new MyObject();
$this->get('event_dispatcher')->addListener(KernelEvents::TERMINATE, function(PostResponseEvent $event) use($myVar) {
    //You logic here
    $request = $event->getRequest();
    $test = $myVar->getMyStuff();
});

But it is not a good practice, please read about normal registering event listeners

kernel.terminate event will be dispatched after sending the response to user.


I am a bit late to the game, but I just found a solution for this problem using the fromShellCommandLine() method:

use Symfony\Component\Process\Process;

Process::fromShellCommandline('/usr/bin/php /var/www/bin/console hello:world')->start();

This way it is possible to start a new process/run a command asynchronously.

Tags:

Php

Symfony