How can I create delays between failed Queued Job attempts in Laravel?

前端 未结 3 2007
野性不改
野性不改 2021-01-04 13:38

I have a queued job in Laravel that fails from time to time because of an external API failing due to high load. The problem is that my choices appear to be to have the Lara

相关标签:
3条回答
  • 2021-01-04 14:25

    What you can do is something like this:

    // app/Jobs/ExampleJob.php
    namespace App\Jobs;
    
    class ExampleJob extends Job
    {
        use \Illuminate\Queue\InteractsWithQueue;
    
        public function handle()
        {
            try {
                // Do stuff that might fail
            } catch(AnException $e) {
                // Example where you might want to retry
    
                if ($this->attempts() < 3) {
                    $delayInSeconds = 5 * 60;
                    $this->release($delayInSeconds);
                }
            } catch(AnotherException $e) {
                // Example where you don't want to retry
                $this->delete();
            }
        }
    }
    

    Please note that you do not have to do this with exceptions, you can also just check the result from your actions and decide from there.

    0 讨论(0)
  • 2021-01-04 14:26

    Laravel 5.8+

    /**
     * The number of seconds to wait before retrying the job.
     *
     * @var int
     */
    public $retryAfter = 3;
    
    0 讨论(0)
  • 2021-01-04 14:31

    You could manually release the job using the Illuminate\Queue\InteractsWithQueue method

    $this->release(10);
    

    The argument will define the amount of seconds until the job is available again.

    Check the section Manually Releasing Jobs in the official documentation for version 5.1.

    0 讨论(0)
提交回复
热议问题