如何在指定队列处运行Laravel作业

Mes*_*uti 3 queue task-queue laravel-5 laravel-5.1 laravel-queue

我有一份工作要执行,将短信发送给用户。我想在指定的队列名称上运行此作业。例如,此作业已添加到“ SMS ”队列中。所以我找到了一种方法,但是存在一些错误。

创建作业实例并使用onQueue()函数执行以下操作

    $resetPasswordJob = new SendGeneratedPasswordResetCode(app()->make(ICodeNotifier::class), [
        'number' => $user->getMobileNumber(),
        'operationCode' => $operationCode
    ]);

    $resetPasswordJob->onQueue('SMS');

    $this->dispatch($resetPasswordJob);
Run Code Online (Sandbox Code Playgroud)

我的Job班级是这样的:

class SendGeneratedPasswordResetCode implements ShouldQueue
{
   use InteractsWithQueue, Queueable;

/**
 * The code notifier implementation.
 *
 * @var ICodeNotifier
 */
protected $codeNotifier;

/**
 * Create the event listener.
 *
 * @param ICodeNotifier $codeNotifier
 * @return self
 */
public function __construct(ICodeNotifier $codeNotifier)
{
    $this->codeNotifier = $codeNotifier;
}

/**
 * Handle the event.
 *
 * @return void
 */
public function handle()
{
    echo "bla blaa bla";
    #$this->codeNotifier->notify($event->contact->getMobileNumber(), $event->code);
}

public function failed()
{
    var_dump("failll");
}
}
Run Code Online (Sandbox Code Playgroud)

因此,我键入以下命令进行控制台:

php artisan queue:listen --queue=SMS --tries=1
Run Code Online (Sandbox Code Playgroud)

但是执行此作业时收到的错误消息:

[InvalidArgumentException]

没有为命令[App \ Services \ Auth \ User \ Password \ SendGeneratedPasswordResetCode]注册的处理程序

注意:另一种方法是将事件添加到EventServiceProvider的listen属性并触发该事件。但这不适用于指定队列名称。

Dan*_*ter 7

您还可以通过在构造上设置Job对象queue属性来指定要放置作业的队列:

class SendGeneratedPasswordResetCode implements ShouldQueue
{
    // Rest of your class before the construct

    public function __construct(ICodeNotifier $codeNotifier)
    {
        $this->queue = 'SMS'; // This states which queue this job will be placed on.
        $this->codeNotifier = $codeNotifier;
    }

    // Rest of your class after construct
Run Code Online (Sandbox Code Playgroud)

然后,您无需->onQueue()在此作业的每个实现/用法上都提供方法,因为Job类本身将为您完成此工作。

我已经在Laravel 5.6中测试过