如何在 Laravel 中失败的排队作业尝试之间创建延迟



>我在Laravel中有一个排队的作业,由于外部API由于高负载而失败,该作业不时失败。问题是我的选择似乎是让 Laravel 队列继续用请求锤击 API,直到它成功,或者告诉它在 X 个请求后停止。

我有什么办法,根据作业失败的方式,告诉它在 5 分钟内重试,而不是继续敲打?

我想使用内置的队列处理程序,但重试功能似乎不是为了处理现实生活中的故障场景而构建的。我认为许多工作失败的原因不会通过立即再次尝试来解决。

你可以做的是这样的:

// app/Jobs/ExampleJob.php
namespace AppJobs;
class ExampleJob extends Job
{
    use IlluminateQueueInteractsWithQueue;
    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();
        }
    }
}

请注意,您不必例外地这样做,您也可以检查您的操作结果并从那里做出决定。

Laravel 8

/**
 * The number of seconds to wait before retrying the job.
 *
 * @var int
 */
public $backoff = 3;

您可以使用 Illuminate\Queue\InteractsWithQueue 方法手动释放作业

$this->release(10);

该参数将定义作业再次可用之前的秒数。

查看版本 5.1 官方文档中的手动释放作业部分。

Laravel 5.8+

/**
 * The number of seconds to wait before retrying the job.
 *
 * @var int
 */
public $retryAfter = 3;

最新更新