Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 run console command in background

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.

like image 441
Ceparu Stefan Avatar asked Oct 31 '22 03:10

Ceparu Stefan


1 Answers

Processes hierarchical

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.

You problem

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).

Solutions for you:

  1. Good idea for runs background commands - use nohup (tutorial)
  2. The vary good idea for any applications - use AMQP protocol between processes. (tutorial via RabbitMQ)

P.S.

In my projects, for runs background tasks, i use RabbitMQ.

like image 136
ZhukV Avatar answered Nov 15 '22 17:11

ZhukV