Set custom timeout for Laravel queued command

Viewed 446

I have a command class like this.

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

Then run this through the queue Artisan::queue('mycommand');

A worker is running for multiple jobs php artisan queue:work --timeout=120

Normally, we can set a custom timeout for a job class like this

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

But how can I achieve this in a Command class properly?

1 Answers

The reason Artisan::queue isn't working for you is because the actual job that gets dispatched is: Illuminate\Foundation\Console\QueuedCommand;

Check out the queue method on the \Illuminate\Foundation\Console\Kernel class

Instead, you should use the Dispatchable trait and implement ShouldQueue while using the ::dispatch() method.

Here's a simple Command doing so:

<?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++);
        }
    }
}

A test to dispatch:

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

        // when

        // then
    }

and the output of the worker (using Horizon)

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


Related