【问题标题】:Set custom timeout for Laravel queued command为 Laravel 排队命令设置自定义超时
【发布时间】:2021-09-07 14:28:43
【问题描述】:

我有一个这样的命令类。

class MyCommand extends Command {
    protected $signature = 'mycommand';
}

然后通过队列运行它 Artisan::queue('mycommand');

一个工人正在为多个作业运行php artisan queue:work --timeout=120

通常,我们可以为这样的作业类设置自定义超时

class MyJob implements ShouldQueue {
    public $timeout = 240; // custom timeout
} 

但是我怎样才能在 Command 类中正确地实现这一点呢?

【问题讨论】:

    标签: php laravel laravel-artisan laravel-queue


    【解决方案1】:

    Artisan::queue 不适合你的原因是因为被派遣的实际工作是:Illuminate\Foundation\Console\QueuedCommand;

    查看\Illuminate\Foundation\Console\Kernel 类中的queue 方法

    相反,您应该使用 Dispatchable 特征并在使用 ::dispatch() 方法时实现 ShouldQueue

    这是一个简单的命令:

    <?php
    
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Foundation\Bus\Dispatchable;
    
    class TestCommand extends Command implements ShouldQueue
    {
        use Dispatchable;
    
        protected $signature = 'test:command';
        protected $description = 'Command description';
        public $timeout = 3;
    
        public function handle()
        {
            $count = 0;
            while (true) {
                sleep(1);
                dump($count++);
            }
        }
    }
    
    

    要分发的测试:

        /** @test */ // test
        public function test(){
            // given
            TestCommand::dispatch();
    
            // when
    
            // then
        }
    
    

    以及worker的输出(使用Horizo​​n)

    2021-07-27 09:55:41][f80e9030-3f04-4148-a99c-42e0ae950947] Processing: App\Console\Commands\TestCommand
    0
    1
    [2021-07-27 09:55:44][f80e9030-3f04-4148-a99c-42e0ae950947] Failed:     App\Console\Commands\TestCommand
    
    
    

    【讨论】:

      猜你喜欢
      • 2021-03-01
      • 2013-08-08
      • 2015-06-30
      • 2015-05-22
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      相关资源
      最近更新 更多