Execute Laravel/Symfony/Artisan Command in Background

依然范特西╮ 提交于 2019-12-22 07:09:12

问题


I need to execute a Laravel long running process in the background for consuming the Twitter Streaming API. Effectively the php artisan CLI command I need to run is

nohup php artisan startStreaming > /dev/null 2>&1 &

If I run that myself in the command line it works perfectly.

The idea is that I can click a button on the website which kicks off the stream by executing the long running artisan command which starts streaming (needs to run in the background because the Twitter Streaming connection is never ending). Going via the command line works fine.

Calling the command programatically however doesn't work. I've tried calling it silently via callSilent() from another command as well as trying to use Symfony\Component\Process\Process to run the artisan command or run a shell script which runs the above command but I can't figure it out.

Update If I queue the command which opens the stream connection, it results in a Process Timeout for the queue worker

I effectively need a way to run the above command from a PHP class/script but where the PHP script does not wait for the completion/output of that command.

Help much appreciated


回答1:


The Symfony Process Component by default will execute the supplied command within the current working directory, getcwd().

The value returned by getcwd() will not be the Laravel install directory (the directory that contains artisan), so the command will most likely returning a artisan: command not found message.

It isn't mentioned in the Process Component documentation but if you take a look at the class file, we can see that the construct allows us to provide a directory as the second parameter.

public function __construct(
    $commandline, 
    $cwd = null, 
    array $env = null, 
    $input = null, 
    $timeout = 60, array 
    $options = array())

You could execute your desired command asynchronously by supplying the second parameter when you initialise the class:

use Symphony\Component\Process\Process;

$process = new Process('php artisan startStreaming > /dev/null 2>&1 &', 'path/to/artisan'); 
$process->start();



回答2:


How about queuing the execution of the command via Laravels build-in queues?



来源:https://stackoverflow.com/questions/32216857/execute-laravel-symfony-artisan-command-in-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!