I've created a console command for my symfony2 project and I want to execute it from a controller without blocking the controller output (in background).
Normally is executed like this:
$application = new Application($kernel);
$application->setAutoExit(true);
// AppBundle/Command/UpdateStockCommand.php
$input = new ArrayInput(array(
'command' => 'update:stock',
));
$output = new NullOutput();
$application->run($input, $output);
But running like this the user will have to wait for the task to be finished which can take several minutes.
A solution is:
$kernel = $this->get('kernel');
$process = new \Symfony\Component\Process\Process('nohup php '. $kernel->getRootDir() .'/console update:stock --env='. $kernel->getEnvironment() .' > /dev/null 2>&1 &');
//$process->start();
$process->run();
No errors given, the controller renders the output, but the task is not executed.
Another solution is:
exec('/usr/bin/php '.$this->get('kernel')->getRootDir().'/console update:stock --env=dev > /dev/null 2>&1 &');
found here Symfony2 - process launching a symfony2 command but doesn't work on my example.
All processes in system have own hierarchical.
As example: we have a Process A
, after the launch of which we run Process B
. If you kill Process A
, then the Process B
killed to, because Process B
is child of Process A
.
The each request (http) Apache create a new child process for run PHP code and return stdoutput to client (Logic of Nginx + PHPFPM - same). And after create child process (via Symfony/Process library
), this process is child of apache or fpm process. After complete request (return response to apache or nginx), the server kill child process (where executed PHP code).
In my projects, for runs background tasks, i use RabbitMQ.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With