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

后端 未结 5 1515
隐瞒了意图╮
隐瞒了意图╮ 2021-02-12 22:30

After a user submits a form, I want to render a view file, and right after that I want to initiate a background task to process five MS Excel files (each may have up to 2000 row

相关标签:
5条回答
  • 2021-02-12 23:11

    I guess what you want is to store the necessary data in a database and then have a cronjob/queue execute the actual command, instead of trying to execute it directly from your controller.

    Add something like the following to your /etc/crontab to let it run your command every 5 minutes

    */5 * * * * root /usr/bin/php /path/to/bin/console hello:world
    

    Then, let your command query the database for the stored data and have it process the excel files

    0 讨论(0)
  • 2021-02-12 23:14

    There is a bundle called AsyncServiceCallBundle which allows you to call your service's methods in background.

    You can refer this answer for more details about how it is done internally. Everything you need is to invoke your service's method as follows:

    $this->get('krlove.async')->call('service_id', 'method', [$arg1, $arg2]);
    
    0 讨论(0)
  • 2021-02-12 23:18

    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.

    0 讨论(0)
  • 2021-02-12 23:25

    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.

    0 讨论(0)
  • 2021-02-12 23:25

    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.

    0 讨论(0)
提交回复
热议问题