如何让 PHP(Laravel 5.2) 在后台休眠

Imr*_*ran 7 php multithreading sleep laravel-5

我创建了一个artisan command我想在调用方法后立即运行的程序。但命令中包含sleep();命令。我想在后台运行该 artisan 命令,因为该方法需要return立即响应用户。我的示例代码如下:

在路线文件中

Route::get('test', function(){
    Artisan::queue('close:bidding', ['applicationId' => 1]);
    return 'called close:bidding';
});
Run Code Online (Sandbox Code Playgroud)

close:bidding指挥中

public function handle()
    {
        $appId = $this->argument('applicationId');
        //following code line is making the problem
        sleep(1000 * 10);
        //close bidding after certain close time
        try{
            Application::where('id', $appId)->update(['live_bidding_status' => 'closed']);
        }catch (\PDOException $e){
            $this->info($e->getMessage());//test purpose
        }
        $this->info($appId.":  bid closed after 10 seconds of creation");
    } 
Run Code Online (Sandbox Code Playgroud)

问题 当我点击url 时,浏览器加载 10 秒后就会显示/test返回字符串,因为命令中有一个。called close:biddingsleep(10 * 1000)

我想要什么 我想在后台运行该命令。我的意思是,当我点击/test网址时,它应该立即显示,called close:biddingclose:bidding命令将在后台运行。10 秒后,它将更新应用程序,但前端用户不会注意到任何有关它的信息。

部分问题

  1. 它有某种关系吗multi threading

  2. 这是 PHP 无法解决的问题吗,我应该换个角度思考吗?

  3. 即使使用 Laravel 队列,有什么办法可以解决这个问题吗?

vij*_*mar 7

创建工作

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class JobTest implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    private $payload = [];
    public function __construct($payload)
    {
        $this->payload = $payload;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $appId = $this->payload('applicationId');
        //following code line is making the problem
        sleep(1000 * 10);
    }
}
Run Code Online (Sandbox Code Playgroud)

推送作业后台队列

Route::get('test', function(){
    dispatch((new JobTest)->onQueue('queue_name'));
    return 'called close:bidding';
});
Run Code Online (Sandbox Code Playgroud)

在这种状态下,我们有作业,您可以将作业调度到队列中。但还没有处理。我们需要队列侦听器或工作人员来在后台处理这些作业

php artisan queue:listen --queue=queue_name --timeout=0  
OR
php artisan queue:work --queue=queue_name --timeout=0 //this will run forever
Run Code Online (Sandbox Code Playgroud)

注意:也许你可以尝试supervisord,beanstakd来管理队列

欲了解更多信息,请参阅