JC Lee
JC Lee

Reputation: 2387

Queued jobs with individual max number of tries, how to?

Normally, the max tries are specified on the queue level like so:

php artisan queue:listen connection-name --tries=3

I would like to be able to override this (without affecting other jobs) on the job level within the job class.

I can think of three ways to go about this but they may not be elegant:

  1. Set a high number of tries on queue level
  2. Look into the failed queue and retry the job
  3. Create a new job upon failure

Note:

  1. My case is related to polling via API.
  2. I am recording my poll attempts within my own model.

Upvotes: 5

Views: 11897

Answers (2)

dsturbid
dsturbid

Reputation: 2086

Since Laravel 5.4, you can specifiy $tries on the job class to override the number of attempts for that job

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 5;

https://laravel.com/docs/5.7/queues#max-job-attempts-and-timeout

Upvotes: 5

xmhafiz
xmhafiz

Reputation: 3538

Try use attempts() method to check current job attempt in the job class. Something like below.

class MyJobClass implements ShouldQueue
{

    public function handle()
    {
        if ($this->attempts() < 3) {
            // do job things
        }
        else {
            // delete job
        }
    }
}

Reference on laravel repository https://github.com/laravel/framework/blob/5.3/src/Illuminate/Queue/InteractsWithQueue.php#L21

Upvotes: 7

Related Questions