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

# 佇列 Job 的重試策略

> 組合使用 Tries、RetryFor、MaxExceptions 與 Backoff，設計 Laravel 13 佇列 Job 在何時、重試幾次以及以何種間隔重試。

設計佇列 Job 的重試時，要把「嘗試幾次」「嘗試到什麼時候」「允許幾次例外」「到下一次嘗試要等幾秒」分開思考。在 Laravel 13 中，這些都可以透過 Job 的 Attribute 與方法來宣告。

> [!NOTE]
>
> 本頁以 Laravel 13 與 Framework `v13.42.0` 為對象。內容不是佇列的基本用法，而是重試設定的組合方式與優先順序。

| 要決定的事項 | Attribute / 方法 | 主要用途 |
| - | - | - |
| 最大嘗試次數 | `#[Tries]` / `tries()` | 為嘗試次數設定上限 |
| 重試期限 | `#[RetryFor]` / `retryUntil()` | 只在派送後的時間範圍內嘗試 |
| 未處理例外的上限 | `#[MaxExceptions]` | 例外達到一定次數後判定失敗 |
| 重試間隔 | `#[Backoff]` / `backoff()` | 決定例外後或手動釋放後的等待時間 |

## 區分嘗試次數與重試期限

Laravel 的「嘗試」不只是 `handle()` 被正常呼叫的次數。未處理例外、`release()`、`WithoutOverlapping` 或 `RateLimited` 等 middleware 造成的釋放，以及逾時，也都會消耗嘗試次數。如果什麼都不指定，worker 只會嘗試 Job 一次。

### `Tries`：為次數設定上限

可以用 `Tries` Attribute 宣告每個 Job 的上限。Job 上的指定優先於 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` 會把重試期限記錄在 Job 的 payload 中。worker 不會再啟動已超過期限的 Job。若 Job 有 `retryUntil()` 方法或 `retryUntil` 屬性，則它們優先於 `RetryFor`。此外，對於 `retryUntil` 生效的 Job，以時間為準的期限優先於 `Tries`。

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

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

`retryUntil()` 適合依 Job 內容動態決定期限的情況，例如外部服務的復原時間或業務上的截止時間。

## 決定未處理例外的上限

有時你希望繼續允許手動 `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 次後判定失敗。
    }
}
```

在這個範例中，Job 最多可以嘗試 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
{
    // ...
}
```

## 設定重試間隔

發生例外的 Job 通常會被重新釋放回佇列。到下一次嘗試的等待時間可以用 `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];
}
```

Job 沒有指定時，會使用 worker 的 `--backoff`。

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

## 以相同的退避釋放等待中的 Job

當外部 API 回傳「處理中」等情況，若想不擲出例外而稍後再次執行 Job，請使用 `releaseUsingBackoff()`。它會使用 Job 所設定的退避陣列中對應目前嘗試的值來釋放。值用完後使用最後一個值，沒有退避時立即釋放。

```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()` 的手動釋放，目的不同。

* **例外時**：Job 無法處理，因此 Laravel 使用退避來釋放。
* **手動釋放**：處理本身正常，但要等外部狀態改變後再稍後執行。

`releaseUsingBackoff()` 的等待時間參照 Job 的 `Backoff` 或 `backoff()`。若想在手動釋放時明確指定其他等待時間，請使用 `release(秒數)`。

## 組合範例

下面的 Job 最多重試 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` 獨立於兩者套用。

## 設定的優先順序

混用 Job 與 worker 的設定時，依下列優先順序思考會比較容易判斷。

| 對象 | 優先的設定 | 備援 |
| - | - | - |
| 最大嘗試次數 | `tries()` | `#[Tries]`、`queue:work --tries` |
| 重試期限 | `retryUntil` 方法 / 屬性 | `#[RetryFor]` |
| 未處理例外的上限 | `#[MaxExceptions]` | 未指定時無上限 |
| 例外後的退避 | `backoff()` | `#[Backoff]`、`queue:work --backoff` |
| 手動釋放的等待時間 | `releaseUsingBackoff()` 使用的 Job 設定 | `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` 也可以指定在進入佇列的事件監聽器與通知上。請確認所使用對象的 payload 具有相同的重試約定。

## 參考連結

* [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 官方文件：失敗 Job 的退避](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

- [2026 年 9 月 Laravel 更新](https://kawax.biz/zh-TW/blog/changelog/202609.md)
- [Queue Job 的執行控制](https://kawax.biz/zh-TW/advanced/queue-job-control.md)
- [Laravel Horizon](https://kawax.biz/zh-TW/horizon.md)
- [Redis](https://kawax.biz/zh-TW/redis.md)
- [Queue 與 Job](https://kawax.biz/zh-TW/queues.md)


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