---
title: "用 WaitFor Timer 轮询"
description: "用 WaitFor Timer 轮询时，每一轮检查一次外部系统，每一轮都是一次新的 Step execution。当 Flow 等待云端构建、资源开通任务或第三方状态，并且想在 Flow 的历史中看到每一轮时，使用这个模式。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-wait-for-timer/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/durable-timer/polling-with-wait-for-timer.mdx"
locale: "zh-Hans"
language: "python"
---

> 供 AI Agent 使用的全部页面索引：https://docs.superdurable.io/zh-Hans/llms.txt

# 用 WaitFor Timer 轮询

本页代码为 Python。其他语言：[Go](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-wait-for-timer.go.md) · [Java](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-wait-for-timer.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-wait-for-timer.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-wait-for-timer.rust.md)

用 WaitFor Timer 轮询时，每一轮检查一次外部系统，每一轮都是一次新的 Step execution。当 Flow 等待云端构建、资源开通任务或第三方状态，并且想在 Flow 的历史中看到每一轮时，使用这个模式。

轮询 Step 在 `WaitFor` 中等待一个 Timer。它的 `Execute` 调用一次外部系统。工作还没完成时，Step 移动到自己，进入下一轮。

**Flow 图：PollingWithTimerFlow**

**Step 列表**

1. `StartJob`（起始 Step）：Start the external job. 下一步：`CheckJobStatus`。
2. `CheckJobStatus`：Wait for the interval Timer, then check the job once. 下一步：`CheckJobStatus`（再次）、Flow 完成、Flow 失败，或 `RecordJobWaitFailure`（持续失败时）。
3. `RecordJobWaitFailure`：Fail the Flow with the reason the status check failed. 下一步：Flow 失败。

例子: [examples/python/dex_examples/patterns/polling-with-timer/polling_with_timer_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/polling-with-timer/polling_with_timer_flow.py)

<a id="shape"></a>

## 结构

轮询 Step 的每一轮执行以下步骤：

1. `WaitFor` 返回一个轮询间隔的 Timer。
2. Timer 触发后，`Execute` 调用一次外部 API，并给这次调用设置自己的短超时。
3. 遇到临时错误时，`Execute` 返回这个错误。重试策略会再次运行这一轮。
4. 遇到终态时，`Execute` 返回下一步的决定：成功或业务失败。
5. 工作还没完成时，`Execute` 返回指向同一个 Step 的 `GoTo`，带上下一轮的输入。

“尚未就绪”是正常的决定。优先用它，而不是返回错误再靠重试循环。返回错误会把“尚未就绪”和真正的失败混在一起，还会消耗重试预算。

<a id="rules"></a>

## 规则

- <a id="not-ready"></a>工作尚未就绪时，返回指向同一个 Step 的 `GoTo`。
  每次 `GoTo` 都开始一次新的 Step execution，它会等待一个新的 Timer。
- <a id="bound-the-loop"></a>给循环设上限。在 Step 输入里带上轮次编号，到达最大值就停止。
  轮次上限限制的是检查次数，不是耗时：每一轮还要花时间在外部调用、重试和排队上。
  需要硬性截止时间时，使用
  [Flow timeout](https://docs.superdurable.io/zh-Hans/reference/python/start-flow-options.md#timeout-and-timeout-policy)（英文）
  或 [截止时间 watchdog](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md#rules)。
- <a id="step-input"></a>Step 输入保持小而且大小固定，例如 job ID 和轮次编号。
  累积的状态，例如收集到的结果，放在 Attribute 里，绝不放进不断变大的 Step 输入。
- <a id="external-calls"></a>在 `Execute` 中检查作业状态。不要在 `WaitFor` 中轮询外部系统。在这个模式中，`WaitFor` 只声明 Timer。
- <a id="retries"></a>`ExecuteRetry` 使用少量带退避的尝试，处理临时错误。
  重试用完后，用 `ExecuteFailure` 选项路由到一个短 Step，由它记录失败；见
  [Execute 失败恢复](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/execute-failure-recovery.md)。
- <a id="interval"></a>Timer 以整秒计时。间隔低于几秒时，使用
  [用长时间运行 Step 的 heartbeat 轮询](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md)。
- <a id="tests"></a>给 Timer 设一个 condition ID。测试里用 `SkipTimer` 跳过它，
  不要缩短间隔；见 [跳过 Timer](https://docs.superdurable.io/zh-Hans/concepts/primitives/timer.md#%E8%B7%B3%E8%BF%87-timer)。

<a id="example"></a>

## 示例

`PollingWithTimerFlow` 等待的模拟 job 与 [heartbeat 示例](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md#example) 相同。`StartJob` 用 Flow ID 作为幂等的 job ID 启动 job。`CheckJobStatus` 等待一个 10 秒的 Timer，然后读取一次 job 状态。job 还在运行时，它带着下一个轮次编号移动到自己。60 轮之后它停止。重试用完时，它移动到 `RecordJobWaitFailure`，由后者用 recovery error 让 Flow 失败。

模拟 job 在启动六秒后成功，所以第一轮就会发现它已完成。调用 complete-job endpoint 可以提前完成它。

**Python**

```python
# MAX_POLL_ROUNDS bounds the number of checks, not elapsed time; calls, retries, and queueing add time.
POLL_INTERVAL = timedelta(seconds=10)
POLL_INTERVAL_TIMER_ID = "poll-interval"
MAX_POLL_ROUNDS = 60
JOB_CALL_TIMEOUT = timedelta(seconds=10)


@dataclass(frozen=True)
class JobPollRound:
    job_id: str
    round_number: int


class CheckJobStatus(Step[JobPollRound]):
    def __init__(self, jobs: FakeJobService) -> None:
        self.jobs = jobs

    def get_step_options(self) -> StepOptions:
        return StepOptions(
            execute_retry=RetryPolicy(
                initial_interval=timedelta(seconds=1),
                backoff_coefficient=2.0,
                maximum_attempts=3,
            ),
        ).on_execute_failure_proceed_to(RecordJobWaitFailure)

    def wait_for(self, context: Context, poll_round: JobPollRound) -> Wait:
        return Wait.until(
            Timer.by_duration(POLL_INTERVAL, condition_id=POLL_INTERVAL_TIMER_ID)
        )

    async def execute(
        self, context: AsyncContext, poll_round: JobPollRound
    ) -> StepDecision:
        status = await asyncio.wait_for(
            self.jobs.get_job_status(poll_round.job_id),
            JOB_CALL_TIMEOUT.total_seconds(),
        )
        if status.state is JobState.SUCCEEDED:
            return graceful_complete(status.result)
        if status.state is JobState.FAILED:
            return force_fail(f"job {poll_round.job_id} failed")
        if poll_round.round_number >= MAX_POLL_ROUNDS:
            return force_fail(
                f"job {poll_round.job_id} did not finish in {MAX_POLL_ROUNDS} rounds"
            )
        next_round = JobPollRound(poll_round.job_id, poll_round.round_number + 1)
        return go_to(CheckJobStatus, next_round)
```

例子: [examples/python/dex_examples/patterns/polling-with-timer/polling_with_timer_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/polling-with-timer/polling_with_timer_flow.py)

<a id="compare"></a>

## 比较两种轮询模式

用 WaitFor Timer 轮询会把每一轮都记录在 Flow 的历史中。你能清楚看到每一轮，也能用 Time Travel 回到某一轮。它稍微重一些。

[用长时间运行 Step 的 heartbeat 轮询](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md) 更轻量。一次 Step execution 承担整个等待。

| 行为                  | WaitFor Timer                                                    | 长时间运行 Step 的 heartbeat                |
| ------------------- | ---------------------------------------------------------------- | ------------------------------------- |
| 每一轮                 | Flow 历史中一次新的 Step execution                                      | 一次尝试内的一次 heartbeat 或一条 Stream message |
| 两轮之间                | 不占用 Worker task slot                                             | 这次尝试一直占用一个 Worker task slot           |
| Dex Server failover | Timer 等待继续，不消耗重试；Worker 已收到的 `WaitFor` 或 `Execute` 尝试会失败，并消耗一次重试 | 正在运行的尝试失败，并消耗一次重试                     |
| 间隔                  | 整秒                                                               | 任意间隔                                  |

准确的 failover 规则，包括 ASYNC 的例外，见 [Lease](https://docs.superdurable.io/zh-Hans/reference/server/high-availability.md#lease)（英文）。

间隔长、要看到每一轮、或者要用 Time Travel 回到某一轮时，选这个模式。间隔短、或者要最轻量的循环时，选 heartbeat 模式。Time Travel 只能回到运行近期历史窗口内的轮次；见 [用 Time Travel 恢复 Flow](https://docs.superdurable.io/zh-Hans/components/operate-and-debug.md#time-travel)。

<a id="next"></a>

## 下一步

- [用长时间运行 Step 的 heartbeat 轮询](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md)
- [Timer](https://docs.superdurable.io/zh-Hans/concepts/primitives/timer.md)
- [提醒](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/reminder.md)
- [Execute 失败恢复](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/execute-failure-recovery.md)
