---
title: "用长时间运行 Step 的 heartbeat 轮询"
description: "用长时间运行 Step 的 heartbeat 轮询，在一次 Step execution 里等待外部系统。当 Flow 等待云端构建、Kubernetes rollout、资源开通任务或第三方 API 的状态，并且想要最轻量的轮询循环时，使用这个模式。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-long-running-step-heartbeat/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.mdx"
locale: "zh-Hans"
language: "python"
---

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

# 用长时间运行 Step 的 heartbeat 轮询

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

用长时间运行 Step 的 heartbeat 轮询，在一次 Step execution 里等待外部系统。当 Flow 等待云端构建、Kubernetes rollout、资源开通任务或第三方 API 的状态，并且想要最轻量的轮询循环时，使用这个模式。

整个等待由一个 Step 负责。它的 `Execute` 调用外部 API，sleep，然后再次调用，直到工作进入终态。[用 WaitFor Timer 轮询](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-wait-for-timer.md) 等待同类系统时，每一轮是一次 Step execution。

Dex 内部的业务信号，例如 Channel message 和 RPC，不属于 polling。用 `WaitFor` 等待它们。TTL、提醒、不活跃截止时间等业务 Timer 也使用 `WaitFor`；见 [持久化定时器](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer.md)。

**Flow 图：PollingFlow**

**Step 列表**

1. `StartJob`（起始 Step）：Start the external job. 下一步：`AwaitJob`。
2. `AwaitJob`：Poll the job with heartbeats until it succeeds or fails. 下一步：Flow 完成、Flow 失败，或 `RecordJobWaitFailure`（持续失败时）。 写入 `JobProgress`。
3. `RecordJobWaitFailure`：Fail the Flow with the reason polling stopped. 下一步：Flow 失败。

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

## 结构

轮询 Step 重复以下步骤：

1. 调用外部 API，并给这次调用设置自己的短超时，例如 10 秒。
2. 遇到临时错误时，返回这个错误。重试策略会再次运行这个 Step。
3. 遇到终态时，返回下一步的决定：成功或业务失败。
4. 报告进度。状态变化时写一条 Stream 消息，否则带着 checkpoint 记录一次 heartbeat。
5. 按轮询间隔 sleep，然后重新开始。

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

普通的 sleep 就够了。通过该语言 SDK 的机制响应取消。外部调用支持取消参数时，把它传进去。观察不到取消的阻塞调用要有自己的 timeout，因为 handler 返回之后 Worker 槽才会释放。取消是协作式的：循环在下一个能报告取消的边界退出。见 [Make the Step stop](https://docs.superdurable.io/zh-Hans/reference/server/runtime-data.md#cancel-honour)（英文）。

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

## 规则

- <a id="interval-and-timeouts"></a>每一轮都要落在 heartbeat 窗口内；计算方法见 [Heartbeat](https://docs.superdurable.io/zh-Hans/reference/python/step-options.md#heartbeat)（英文）。用户正在等待时，间隔用几秒；构建这类长任务，用几十秒。
- <a id="limits"></a>`ExecuteMethodTimeout` 和 `TotalDuration` 使用同一个最长等待时间。Dex 会强制执行这两个值，所以 Step 不需要自己计算截止时间。失败之后，`TotalDuration` 只决定是否安排下一次尝试。排队可能让已安排的尝试晚开始，进行中的尝试也不会被截断，所以整个等待可能比它晚很多才结束。Flow 的业务截止时间用下面的 watchdog。`ExecuteRetry` 使用少量带退避的尝试，用于处理临时错误和 Worker 崩溃。见 [Timeouts 和 total duration](https://docs.superdurable.io/zh-Hans/reference/python/step-options.md#timeouts-and-total-duration)（英文）。Polling Step 可以使用任一种 durability。
- <a id="when-the-wait-expires"></a>等待超时后，Step 失败。用 `ExecuteFailure` 选项把这个失败路由到一个短 Step，由它记录业务失败；见 [Execute 失败恢复](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/execute-failure-recovery.md)。失败记录不包含最后的状态；从 Stream 或日志中读取它。
- 其他业务条件仍然在循环中检查，例如由其他系统持有、可能过期的 lease。这些 timeout 只能限定固定时长。
- <a id="deadline-watchdog"></a>业务截止时间比整个等待短，或者轮询 Step 为了提交每次状态变化而重新进入自身、Step options 无法守住截止时间时，使用 watchdog。watchdog 是一个与自己的 Timer 竞争的等待 Step。它和记录结果的 Step 声明同一个 Attribute lock。Timer 触发时，它在这个 lock 下读取状态，只有工作仍未完成时才判定超期。
- <a id="checkpoint-and-progress"></a>从上一个 checkpoint 继续，用 `GetLastHeartbeatValue` 读取它。示例中的 checkpoint 是上一次报告的 job 状态。从最后存储的 checkpoint 继续，可以减少重试后重复发送的进度消息。checkpoint 可能丢失，所以消费方必须容忍重复和缺失的消息；见 [Heartbeat](https://docs.superdurable.io/zh-Hans/reference/python/step-options.md#heartbeat)（英文）。
- 只在观察到的状态变化时写入一条 Stream message，其余轮次记录 heartbeat。Stream message 是 best-effort，所以消费方从持久化状态恢复，例如 Attribute、读取 RPC 或 Flow 结果。
- <a id="locks"></a>由 polling Step 返回结果，需要加锁提交的内容放到随后一个短 Step 中。如果 polling Step 在整个等待期间持有 lock，需要它的 Step（例如 watchdog）都要等到循环结束，需要它的 RPC 都会失败。

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

## 示例

`PollingFlow` 等待一个模拟的外部 job。`StartJob` 以 Flow ID 作为幂等 job ID 启动 job。`AwaitJob` 每两秒查询一次 job 状态。状态变化时写入一条 `JobProgress` Stream message，并以 job 结果完成。每次尝试最多持续十分钟。失败之后，十分钟的重试预算决定是否开始下一次尝试。Dex 不再开始新的尝试时，`AwaitJob` 移动到 `RecordJobWaitFailure`。这个 Step 以恢复错误让 Flow 失败。

模拟 job 先报告 QUEUED，然后是 RUNNING，启动六秒后成功。调用 complete-job endpoint 可以让它提前完成。

**Python**

```python
# Keep POLL_INTERVAL + JOB_CALL_TIMEOUT <= heartbeat_timeout - 10s.
# MAX_JOB_WAIT bounds each attempt and whether another attempt starts; Dex enforces it.
POLL_INTERVAL = timedelta(seconds=2)
JOB_CALL_TIMEOUT = timedelta(seconds=10)
MAX_JOB_WAIT = timedelta(minutes=10)

JOB_PROGRESS = Stream("JobProgress", JobStatus, 1 << 20)


class RecordJobWaitFailure(Step[str]):
    def execute(self, context: Context, job_id: str) -> StepDecision:
        failure = context.recovery_error
        assert failure is not None
        return force_fail(
            f"waiting for job {job_id} failed: {failure.error_type}: {failure.detail}"
        )


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

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

    async def execute(self, context: AsyncContext, job_id: str) -> StepDecision:
        reported_state = context.get_last_heartbeat_value(JobState)
        while True:
            status = await self.get_job_status(job_id)
            if status.state is JobState.SUCCEEDED:
                return graceful_complete(status.result)
            if status.state is JobState.FAILED:
                return force_fail(f"job {job_id} failed")
            if status.state != reported_state:
                JOB_PROGRESS.write(context, status)
                reported_state = status.state
            else:
                await context.heartbeat(reported_state)
            await asyncio.sleep(POLL_INTERVAL.total_seconds())

    async def get_job_status(self, job_id: str) -> JobStatus:
        return await asyncio.wait_for(
            self.jobs.get_job_status(job_id), JOB_CALL_TIMEOUT.total_seconds()
        )
```

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

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

## 比较两种轮询模式

长时间运行的 Step 加 heartbeat 更轻量。一次 Step execution 承担整个等待。

[用 WaitFor Timer 轮询](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-wait-for-timer.md) 会把每一轮都记录在 Flow 的历史中。你能清楚看到每一轮，也能用 Time Travel 回到某一轮。它稍微重一些。

| 行为                  | 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 回到某一轮时，选 Timer 模式。Time Travel 只能回到运行近期历史窗口内的轮次；见 [用 Time Travel 恢复 Flow](https://docs.superdurable.io/zh-Hans/components/operate-and-debug.md#time-travel)。

## 下一步

- [外部交互](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction.md)
- [用 WaitFor Timer 轮询](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-wait-for-timer.md)
- [Step options](https://docs.superdurable.io/zh-Hans/reference/python/step-options.md#timeouts-and-total-duration)
- [Stream](https://docs.superdurable.io/zh-Hans/concepts/primitives/stream.md)
- [失败处理](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling.md)
- [Execute 失败恢复](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/execute-failure-recovery.md)
