> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 队列任务的重试策略

> 组合使用 Tries、RetryFor、MaxExceptions 和 Backoff，设计 Laravel 13 队列任务在何时、重试多少次以及以何种间隔重试。

设计队列任务的重试时，要把"尝试几次""尝试到什么时候""允许多少次异常""到下一次尝试等待几秒"分开考虑。在 Laravel 13 中，这些都可以通过任务的 Attribute 和方法来声明。

> [!NOTE]
>
> 本页面向 Laravel 13 和 Framework `v13.42.0`。内容不是队列的基本用法，而是重试设置的组合方式与优先级。

| 要决定的事项 | Attribute / 方法 | 主要用途 |
| - | - | - |
| 最大尝试次数 | `#[Tries]` / `tries()` | 为尝试次数设置上限 |
| 重试期限 | `#[RetryFor]` / `retryUntil()` | 仅在投递后的时间窗口内尝试 |
| 未处理异常的上限 | `#[MaxExceptions]` | 异常达到一定次数后判定失败 |
| 重试间隔 | `#[Backoff]` / `backoff()` | 决定异常后或手动释放后的等待时间 |

## 区分尝试次数和重试期限

Laravel 的"尝试"并不只是 `handle()` 被正常调用的次数。未处理异常、`release()`、`WithoutOverlapping` 或 `RateLimited` 等中间件导致的释放以及超时也会消耗尝试次数。如果什么都不指定，worker 只会尝试任务一次。

### `Tries`：为次数设置上限

可以用 `Tries` Attribute 声明每个任务的上限。任务上的指定优先于 worker 的 `--tries`。

```php theme={null}
<?php

namespace App\Jobs;

use Illuminate\Queue\Attributes\Tries;

#[Tries(5)]
class ProcessInvoice implements ShouldQueue
{
    // ...
}
```

如果要根据运行时条件决定上限，请使用 `tries()` 方法。该方法优先于 `Tries` Attribute。

```php theme={null}
public function tries(): int
{
    return $this->invoice->isLarge() ? 10 : 3;
}
```

### `RetryFor`：指定时间窗口

如果不按次数，而是按投递到队列后可重试的时间来限制，请使用 `RetryFor`。不带名称的位置参数表示秒数，也可以用命名参数指定 `minutes` 和 `hours`。

```php theme={null}
use Illuminate\Queue\Attributes\RetryFor;

#[RetryFor(hours: 1)]
class ProcessInvoice implements ShouldQueue
{
    // ...
}
```

以下指定分别表示秒、分钟和小时。

```php theme={null}
#[RetryFor(90)]
#[RetryFor(minutes: 10)]
#[RetryFor(hours: 4)]
#[RetryFor(hours: 1, minutes: 30)]
```

`RetryFor` 会把重试期限记录在任务的负载中。worker 不会再启动已超过期限的任务。如果任务有 `retryUntil()` 方法或 `retryUntil` 属性，则它们优先于 `RetryFor`。另外，对于 `retryUntil` 生效的任务，基于时间的期限优先于 `Tries`。

```php theme={null}
use DateTime;

public function retryUntil(): DateTime
{
    return now()->plus(minutes: 30);
}
```

`retryUntil()` 适合根据任务内容动态决定期限的场景，例如外部服务的恢复时间或业务截止时间。

## 决定未处理异常的上限

有时你希望继续允许手动 `release()` 或等待获取锁时的释放，但在未处理异常持续发生时尽早失败。这种情况下，请分别指定 `Tries` 和 `MaxExceptions`。

```php theme={null}
use Illuminate\Queue\Attributes\MaxExceptions;
use Illuminate\Queue\Attributes\Tries;

#[Tries(25)]
#[MaxExceptions(3)]
class ProcessInvoice implements ShouldQueue
{
    public function handle(): void
    {
        // 允许通过 release() 重试，
        // 未处理异常发生 3 次后判定失败。
    }
}
```

在这个例子中，任务最多可以尝试 25 次。但如果未处理异常发生 3 次，即使尚未达到尝试次数上限也会失败。`MaxExceptions` 并不是用来统计 `release()` 导致的重试次数的设置。

默认情况下，进程因内存不足等原因崩溃的尝试不计入 `MaxExceptions` 的异常数。如果崩溃也需要算作异常，请添加 `CountCrashesAsExceptions`。

```php theme={null}
use Illuminate\Queue\Attributes\CountCrashesAsExceptions;
use Illuminate\Queue\Attributes\MaxExceptions;

#[CountCrashesAsExceptions]
#[MaxExceptions(3)]
class ProcessInvoice implements ShouldQueue
{
    // ...
}
```

## 设置重试间隔

发生异常的任务通常会被重新释放回队列。到下一次尝试的等待时间可以通过 `Backoff` Attribute 或 `backoff()` 方法设置。

### 固定间隔

```php theme={null}
use Illuminate\Queue\Attributes\Backoff;

#[Backoff(10)]
class ProcessInvoice implements ShouldQueue
{
    // 未处理异常后，等待 10 秒再重试。
}
```

指定数组时，可以为每次尝试设置不同的间隔。数组元素用完后会使用最后一个值。

```php theme={null}
#[Backoff([10, 30, 60])]
class ProcessInvoice implements ShouldQueue
{
    // 第 1 次重试前等待 10 秒，第 2 次前等待 30 秒，
    // 第 3 次及以后等待 60 秒。
}
```

如果要根据条件改变间隔，请使用 `backoff()`。`backoff()` 优先于 `Backoff` Attribute。

```php theme={null}
public function backoff(): int|array
{
    return $this->invoice->isFromExternalProvider()
        ? [30, 60, 300]
        : [5, 15, 30];
}
```

任务没有指定时，会使用 worker 的 `--backoff`。

```shell theme={null}
php artisan queue:work redis --tries=3 --backoff=10
```

## 以相同的退避释放等待中的任务

当外部 API 返回"处理中"等情况下，如果想不抛出异常而稍后再次执行任务，请使用 `releaseUsingBackoff()`。它会使用任务所设置的退避数组中与当前尝试对应的值来释放任务。值用完后使用最后一个值，没有退避时立即释放。

```php theme={null}
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;

#[Backoff([10, 30, 60])]
class CheckPaymentStatus implements ShouldQueue
{
    use Queueable;

    public function handle(): void
    {
        if ($this->paymentIsPending()) {
            $this->releaseUsingBackoff();

            return;
        }

        // 支付完成后的处理
    }

    private function paymentIsPending(): bool
    {
        // 确认支付服务的状态。
        return true;
    }
}
```

异常时的自动释放与通过 `releaseUsingBackoff()` 的手动释放，目的不同。

* **异常时**：任务未能处理，因此 Laravel 使用退避来释放。
* **手动释放**：处理本身正常，但要等外部状态变化后再稍后执行。

`releaseUsingBackoff()` 的等待时间参照任务的 `Backoff` 或 `backoff()`。如果想在手动释放时明确指定其他等待时间，请使用 `release(秒数)`。

## 组合示例

下面的任务最多重试 1 小时，最多允许 3 次未处理异常。在异常时或等待支付的手动释放中，使用 10 秒、30 秒、60 秒的间隔。

```php theme={null}
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\MaxExceptions;
use Illuminate\Queue\Attributes\RetryFor;
use Illuminate\Queue\Attributes\Tries;

#[Tries(25)]
#[RetryFor(hours: 1)]
#[MaxExceptions(3)]
#[Backoff([10, 30, 60])]
class ProcessInvoice implements ShouldQueue
{
    use Queueable;

    public function handle(): void
    {
        // 调用外部服务处理发票。
    }
}
```

存在 `RetryFor` 时，worker 会以期限而不是 `Tries(25)` 作为常规的尝试上限。如果两者都指定，请决定**以基于时间的期限为主，还是以基于次数的上限为主**，并用测试固定这一意图。`MaxExceptions` 独立于两者生效。

## 设置的优先级

混合使用任务和 worker 的设置时，按以下优先级考虑会更容易判断。

| 对象 | 优先的设置 | 回退 |
| - | - | - |
| 最大尝试次数 | `tries()` | `#[Tries]`、`queue:work --tries` |
| 重试期限 | `retryUntil` 方法 / 属性 | `#[RetryFor]` |
| 未处理异常的上限 | `#[MaxExceptions]` | 未指定时无上限 |
| 异常后的退避 | `backoff()` | `#[Backoff]`、`queue:work --backoff` |
| 手动释放的等待时间 | `releaseUsingBackoff()` 使用的任务设置 | `release(秒数)` |

存在由 `retryUntil` 或 `RetryFor` 设定的期限时，worker 会优先于 `tries` 的次数考虑期限。同时使用 `RetryFor` 和 `retryUntil()` 时，动态的 `retryUntil()` 优先。

## 如何选择

```mermaid theme={null}
flowchart TD
    A["决定重试条件"] --> B{"按次数停止？"}
    B -->|是| C["#[Tries]"]
    B -->|否| D["#[RetryFor] 或 retryUntil()"]
    C --> E{"仅在未处理异常时尽早失败？"}
    D --> E
    E -->|是| F["#[MaxExceptions]"]
    E -->|否| G["不需要"]
    F --> H{"改变等待时间？"}
    G --> H
    H -->|是| I["#[Backoff] / backoff()"]
    H -->|等待状态| J["releaseUsingBackoff()"]
    H -->|否| K["worker 的默认值"]
```

* 等待外部服务恢复的期限明确时用 `RetryFor`，期限在运行时才确定时用 `retryUntil()`。
* API 的速率限制或支付状态的确认，使用 `Backoff` 和 `releaseUsingBackoff()`。
* 想大量允许临时的锁等待、同时减少实际异常时，组合使用 `Tries` 和 `MaxExceptions`。
* 对于重试会叠加副作用的处理，不仅要设计尝试次数，还要设计幂等性以及外部 API 侧的重复控制。

> [!NOTE]
>
> `Tries` 和 `RetryFor` 也可以指定在进入队列的事件监听器和通知上。请确认所使用对象的负载具有相同的重试约定。

## 参考链接

* [Laravel 官方文档：Max job attempts and timeout](https://github.com/laravel/docs/blob/13.x/queues.md#max-job-attempts-and-timeout)
* [Laravel 官方文档：Time-based attempts](https://github.com/laravel/docs/blob/13.x/queues.md#time-based-attempts)
* [Laravel 官方文档：手动释放与 `releaseUsingBackoff`](https://github.com/laravel/docs/blob/13.x/queues.md#manually-releasing-a-job)
* [Laravel 官方文档：失败任务的退避](https://github.com/laravel/docs/blob/13.x/queues.md#dealing-with-failed-jobs)
* [`RetryFor` Attribute](https://github.com/laravel/framework/blob/v13.42.0/src/Illuminate/Queue/Attributes/RetryFor.php)
* [`Backoff`、`Tries`、`MaxExceptions` Attribute](https://github.com/laravel/framework/tree/v13.42.0/src/Illuminate/Queue/Attributes)
* [`Queue::getJobExpiration`](https://github.com/laravel/framework/blob/v13.42.0/src/Illuminate/Queue/Queue.php)
* [`InteractsWithQueue::releaseUsingBackoff`](https://github.com/laravel/framework/blob/v13.42.0/src/Illuminate/Queue/InteractsWithQueue.php)


## Related topics

- [队列任务的执行控制](https://kawax.biz/zh-CN/advanced/queue-job-control.md)
- [包的队列任务与更新时的兼容性](https://kawax.biz/zh-CN/advanced/package-queue-jobs.md)
- [队列与任务](https://kawax.biz/zh-CN/queues.md)
- [2026 年 9 月 Laravel 更新](https://kawax.biz/zh-CN/blog/changelog/202609.md)
- [使用 Orchestra Testbench 测试 Laravel 包](https://kawax.biz/zh-CN/advanced/package-testing.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.