Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run custom Symfony2 command in background

Tags:

php

symfony

Symfony2 enables developers to create their own command-line commands. They can be executed from command line, but also from the controller. According to official Symfony2 documentation, it can be done like that:

protected function execute(InputInterface $input, OutputInterface $output)
{
    $command = $this->getApplication()->find('demo:greet');

    $arguments = array(
        ...
    );

    $input = new ArrayInput($arguments);
    $returnCode = $command->run($input, $output);

}

But in this situation we wait for the command to finish it's execution and return the return code.

How can I, from controller, execute command forking it to background without waiting for it to finish execution?

In other words what would be equivalent of

$ nohup php app/console demo:greet &
like image 239
malloc4k Avatar asked Dec 10 '12 14:12

malloc4k


2 Answers

From the documentation is better use start() instead run() if you want to create a background process. The process_max_time could kill your process if you create it with run()

"Instead of using run() to execute a process, you can start() it: run() is blocking and waits for the process to finish, start() creates a background process."

like image 177
Freenando Avatar answered Nov 15 '22 04:11

Freenando


According to the documentation I don't think there is such an option: http://api.symfony.com/2.1/Symfony/Component/Console/Application.html

But regarding what you are trying to achieve, I think you should use the process component instead:

use Symfony\Component\Process\Process;

$process = new Process('ls -lsa');
$process->run(function ($type, $buffer) {
    if ('err' === $type) {
        echo 'ERR > '.$buffer;
    } else {
        echo 'OUT > '.$buffer;
    }
});

And as mentioned in the documentation "if you want to be able to get some feedback in real-time, just pass an anonymous function to the run() method".

http://symfony.com/doc/master/components/process.html

like image 6
cheesemacfly Avatar answered Nov 15 '22 04:11

cheesemacfly