简体   繁体   English

如何从排队的作业中启动工匠命令,然后使用数据库驱动程序执行后删除作业

[英]How to launch an artisan command from a queued Job then delete the Job after execution using database driver

I'm using database driver to queue my jobs. 我正在使用数据库驱动程序来排队我的工作。 I need to call an artisan command from a queued Job and when the Job has finished I need to remove it from the queue. 我需要从排队的作业中调用工匠命令,当作业完成后,我需要将其从队列中删除。 This is my controller's code where I add the job in the queue 这是我的控制器的代码,我在队列中添加作业

dispatch((new SendNewsletter())->onQueue('newsletter'));

This is my queued Job 这是我排队的工作

<?php

namespace App\Jobs;

use App\Console\Commands\Newsletter;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

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

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        app()->make(Newsletter::class)->handle();
    }
}

The artisan command I need to call is App\\Console\\Commands\\Newsletter 我需要调用的artisan命令是App\\Console\\Commands\\Newsletter

and when the Job ends, this should remove it from the queue. 作业结束时,应将其从队列中删除。 This is AppServiceProvider class 这是AppServiceProvider类

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot() {
    Queue::after(function ($event) {
        if ($event->job->queue == 'newsletter') {
            $event->job->delete();
        }
    });
}

The Job is added correctly to the database queue and when I run php artisan queue:work the job is called multiple times endless. 作业已正确添加到数据库队列中,当我运行php artisan queue:work该作业被多次调用。 seems that Queue::after's callback is never called. 似乎从未调用Queue :: after的回调。 any idea what am I missing ? 知道我想念什么吗?

Probably your job fails and it is added to queue trying to finsh the work correctly. 您的工作可能失败,并且将其添加到队列中以尝试正确完成工作。 Try calling the command in your job like this 尝试像这样在工作中调用命令

\Artisan::call('your:command');

Instead of: 代替:

app()->make(Newsletter::class)->handle();

Where "your:command" is the command name, that you gave in the command class: 其中“ your:command”是您在命令类中输入的命令名称:

protected $signature = 'email:send {user}';

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

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