Laravel - Queues - Dealing With Failed Jobs
Sometimes your queued jobs will fail. Don't worry, things don't always go as planned! Laravel includes a convenient way to specify the maximum number of times a job should be attempted. After a job has exceeded this number of attempts, it will be inserted into the failed_jobs
database table. Of course, we will need to create that table if it does not already exist. To create a migration for the failed_jobs
table, you may use the queue:failed-table
command:
php artisan queue:failed-table
php artisan migrate
When running a queue worker process, you may specify the maximum number of times a job should be attempted using the --tries
switch on the queue:work
command. If you do not specify a value for the --tries
option, jobs will only be attempted once or as many times as specified by the job class' $tries
property:
php artisan queue:work redis --tries=3
Using the --backoff
option, you may specify how many seconds Laravel should wait before retrying a job that has encountered an exception. By default, a job is immediately released back onto the queue so that it may be attempted again:
php artisan queue:work redis --tries=3 --backoff=3
If you would like to configure how many seconds Laravel should wait before retrying a job that has encountered an exception on a per-job basis, you may do so by defining a backoff
property on your job class:
/**
* The number of seconds to wait before retrying the job.
*
* @var int
*/
public $backoff = 3;
If you require more complex logic for determining the job's backoff time, you may define a backoff
method on your job class:
/**
* Calculate the number of seconds to wait before retrying the job.
*
* @return int
*/
public function backoff()
{
return 3;
}
You may easily configure "exponential" backoffs by returning an array of backoff values from the backoff
method. In this example, the retry delay will be 1 second for the first retry, 5 seconds for the second retry, and 10 seconds for the third retry:
/**
* Calculate the number of seconds to wait before retrying the job.
*
* @return array
*/
public function backoff()
{
return [1, 5, 10];
}