繁体   English   中英

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

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

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

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

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

你可以做的是这样的:

// 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();
        }
    }
}

请注意,您不必在例外情况下执行此操作,您也可以仅检查操作的结果并从那里做出决定。

您可以使用 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;

Laravel 8

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM