简体   繁体   English

Laravel 5.8 - 从控制台命令执行后台作业

[英]Laravel 5.8 - execute background job from console command

My project is based on Laravel 5.8.我的项目基于 Laravel 5.8。
I have a console command which perform some heavy tasks (generating very big PDF files, sending massive emails, etc.)我有一个控制台命令可以执行一些繁重的任务(生成非常大的 PDF 文件、发送大量电子邮件等)

I tried to move these tasks to a background processes using jobs .我尝试使用jobs将这些任务移动到后台进程。
Here is what I did in order to test how it works:这是我为了测试它是如何工作而做的:

php artisan make:job TestJob

The job file:作业文件:

class TestJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $data;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        sleep(5);
        $date = new \DateTime();
        $currentDateTime = $date->format('Ymd-His');
        $logFileName = "logs/testjob-$currentDateTime.log";
        $content = var_export($this->data, true);
        $res = Storage::disk('local')->put($logFileName, $content);
        echo "[TestJob] Print to log file: $logFileName\n";
    }
}

Console command file:控制台命令文件:

public function handle()
{
    echo "[Console Command] Starting...\n";

    $someData = [
        'First name' => 'John',
        'Surname' => 'Doe'
    ];
    TestJob::dispatch($someData);
    echo "[Console Command] Finished!\n";
}

On execution, this is the output:执行时,这是输出:

[Console Command] Starting...
                                                                <<< delay 5 sec.   
[TestJob] Print to log file: logs/testjob-20210628-114321.log
[Console Command] Finished!

The problem:问题:
The job is executed inside the script, and not in background .作业在脚本内执行,而不是在后台执行

What should I do to make it run in background?我该怎么做才能让它在后台运行?

You should change your queue connection (driver) from sync to redis (or another supported queue driver).您应该将队列连接(驱动程序)从同步更改为 redis(或其他支持的队列驱动程序)。 You can do it in your .env file (for example: QUEUE_CONNECTION=database).您可以在 .env 文件中执行此操作(例如:QUEUE_CONNECTION=database)。

https://laravel.com/docs/5.8/queues#driver-prerequisites https://laravel.com/docs/5.8/queues#driver-prerequisites

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM