【问题标题】:How to run a Laravel Job at specify Queue如何在指定队列运行 Laravel 作业
【发布时间】:2017-01-14 08:15:52
【问题描述】:

我有一个工作来向用户发送短信。我想在指定的队列名称上运行此作业。例如,此作业添加到“SMS”队列。所以我找到了一种方法来做到这一点,但它存在一些错误。

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

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

    $resetPasswordJob->onQueue('SMS');

    $this->dispatch($resetPasswordJob);

我的工作类是这样的:

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");
}
}

所以我在控制台输入这个命令:

php artisan queue:listen --queue=SMS --tries=1

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

[无效参数异常]

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

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

【问题讨论】:

  • 那么,您是否为 SendGeneratedPasswordResetCode 注册了一个处理程序?
  • 当我为 Job 注册一个处理程序时,它会将这项工作添加到默认队列中。这已经是真正的问题了。我想添加指定队列。

标签: laravel-5 queue laravel-5.1 task-queue laravel-queue


【解决方案1】:

您还可以通过在构造上设置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

然后,您不需要在此作业的每个实现/使用中提供 ->onQueue() 方法,因为 Job 类本身会为您完成。

我已经在 Laravel 5.6 中测试过了

【讨论】:

    猜你喜欢
    • 2017-12-02
    • 2016-09-01
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多