---
title: "控制长时间运行的工作"
description: "控制长时间运行的工作（Control Long-Running Work，原名“停止长时间运行的工作”（Stop Long-Running Work）和“可中断执行”（Interruptible execution））用来调整或停止正在运行的循环。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/control-long-running-work/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/external-interaction/control-long-running-work.mdx"
locale: "zh-Hans"
language: "python"
---

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

# 控制长时间运行的工作

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

控制长时间运行的工作（Control Long-Running Work，原名“停止长时间运行的工作”（Stop Long-Running Work）和“可中断执行”（Interruptible execution））用来调整或停止正在运行的循环。

这个模式适合长时间循环运行的工作，例如数据回填或批处理。调用方可以调整循环的工作方式，例如每一轮加载多少条数据。调用方也可以要求循环停止。如果要等待外部系统，请改用 [用 WaitFor Timer 轮询](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-wait-for-timer.md) 或 [用长时间运行 Step 的 heartbeat 轮询](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md)。

**Flow 图：RecordBackfillFlow**

**Step 列表**

1. `StartRecordBackfill`（起始 Step）：Start the backfill at the first record. 下一步：`ProcessRecordBatch`。
2. `ProcessRecordBatch`：Read the controls, then process one batch of records or stop. 下一步：Flow 完成，或 `ProcessRecordBatch`（再次）。 读取 `batchSize`、`stopRequested`。

**RPC 列表**

- `request_stop`：写入 `stopRequested`。
- `set_batch_size`：写入 `batchSize`。

例子: [examples/python/dex_examples/patterns/control-long-running-work/record_backfill_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/control-long-running-work/record_backfill_flow.py)

<a id="control-a-running-loop"></a>

## 控制正在运行的循环

1. 一个 RPC 写入控制 Attribute，例如批量大小和停止请求。
2. 循环 Step 在两轮之间等待，例如等待一个 Timer。
3. 每一轮在 `Execute` 开始时读取控制 Attribute。
4. 已请求停止时，`Execute` 完成。否则它按当前的控制值处理一个单元。
5. `Execute` 回到同一个 Step，把下一个位置作为输入。

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

## 规则

- 循环位置放在 Step 输入里。控制值放在 Attribute 里。
- 新的控制值从下一轮开始生效。正在运行的这一轮使用它已经读到的值。
- RPC 在写入之前校验每个值。这样循环读到的控制值总是有效的。
- 控制值未设置时，在读取时使用默认值。如果由开始 Step 写入默认值，可能会覆盖先到达的 RPC 写入的值。

<a id="attribute-or-channel"></a>

## 选择 Attribute 还是 Channel

| 控制                 | Primitive | 原因                                               |
| ------------------ | --------- | ------------------------------------------------ |
| 参数，例如批量大小、速率或暂停标志  | Attribute | 最新的值生效。循环只需要当前值。                                 |
| 针对某一条数据的命令，例如跳过或重试 | Channel   | 已接受的命令按 FIFO 顺序排队，由唯一的消费者按这个顺序取出。后来的命令不会替换先前的命令。 |

要从 Channel 接收命令，循环用 `AnyOf` 同时等待 Timer 和这个 Channel。`AnyOf` 只为胜出的 Channel 分支消费消息。`Execute` 先判断哪个分支胜出：Channel 胜出时处理消费到的命令，Timer 胜出时处理下一批数据。之后到达的命令留在队列里，由后面的某一轮处理。

如果循环停止前必须处理完每一条已接受的命令，就在 Flow 关闭前排空这个 Channel。外部调用方可能同时发布时，用原子的 complete-if-empty 决策关闭 Flow，做法见 [排空外部 Channel](https://docs.superdurable.io/zh-Hans/design-patterns/draining-channel-for-external-publishing.md)。

<a id="choose-how-to-stop"></a>

## 选择停止方式

Dex 内置三种停止工作的方式。按哪些工作必须停、哪些工作还要继续来选择。

| 方式                  | 停止什么                                                         | 适用场景                       |
| ------------------- | ------------------------------------------------------------ | -------------------------- |
| StopFlow            | 整个运行，立即停止                                                    | 运行必须马上结束，也没有 Step 需要汇报或清理。 |
| Graceful completion | 等待 graceful completion Condition 的 Step；没有活跃的 Step 时 Flow 完成 | Flow 应先做完当前的工作，然后完成。       |
| Step 取消             | 选定的正在运行的 Step                                                | 一个分支必须停止，Flow 的其余部分继续运行。   |

<a id="finish-the-current-unit-then-stop"></a>

下面的示例把停止请求和其他控制值一起放在控制 Attribute 里。循环读取它，并在下一个单元开始前停止。如果循环的等待包含 graceful completion Condition，graceful completion 也能停止这样的循环，这时不需要停止 Attribute。

<a id="stopflow"></a>

### 用 StopFlow 停止整个运行

客户端调用 `StopFlow` 来取消（cancel）、失败（fail）或终止（terminate）这个运行。每种类型记录不同的终止状态。stop 一提交，运行就关闭。

stop 提交后，只有已经在运行的 handler 还能继续运行。之后的 Step 决定、失败路由和清理都不会运行。正在运行的 Step 会收到取消信号。忽略这个信号的 handler 会继续运行，它对外部系统的调用仍然生效。Dex 会丢弃它未提交的结果。等待这个 Flow 的一方读取它的终止状态，而不是等它汇报。

当 Flow 里没有工作需要做完、也没有清理需要运行时，使用 StopFlow。各种 stop 类型见 [Stop a Flow](https://docs.superdurable.io/zh-Hans/reference/server/runtime-client.md#stop-a-flow)（英文）。

<a id="graceful-completion"></a>

### 请求 Flow graceful completion

Flow 收到 graceful completion 请求：客户端用 graceful complete 调用 `StopFlow`，或者某个 Step 返回 `GracefulComplete`。正在运行的 Step 继续运行，它们的决定仍然生效。没有活跃的 Step 时，Flow 完成。

等待中的 Step 如果包含 graceful completion Condition，请求到达时就停止等待。它的 `Execute` 先处理已经消费的消息。没有消息时，它结束自己的分支。等待中不含这个 Condition 的 Step 会继续运行，让 Flow 保持打开。通过 Timer 和 `GoTo` 进入下一个单元的循环会一直循环，直到它自己检查这个请求。

当每个分支应先做完当前单元再停止时，使用 graceful completion。在每个本来会让分支一直存活的等待里加上这个 Condition。所有 SDK 都提供 graceful completion Condition：Go、Python、Java、TypeScript 和 Rust。见 [Wait for a completion request](https://docs.superdurable.io/zh-Hans/reference/server/step-and-flow-close.md#graceful-completion-condition)（英文）。

<a id="cancel-running-steps"></a>

### 取消正在运行的 Step

Step 决定或 RPC 可以取消选定的活跃 Step，例如按 Step 类型取消。Flow 的其余部分继续运行。SDK 把取消信号传给每个被取消的 handler。handler 检查这个信号并返回。Dex 丢弃被取消 Step 之后的结果。

要停止一个分支时使用 Step 取消，例如用户不再需要的一个任务。被取消 Step 消费的消息通常会回到它们的 Channel，所以每个 handler 都要保持幂等。见 [Step cancellation](https://docs.superdurable.io/zh-Hans/reference/server/step-and-flow-close.md#step-cancellation)（英文）。

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

## 示例

<a id="core-implementation"></a>

`RecordBackfillFlow` 分批处理 1000 条记录。`StartRecordBackfill` 从第一条记录开始，进入 `ProcessRecordBatch`。`ProcessRecordBatch` 在两批之间等待一秒。每次 `Execute` 先读取 `stopRequested` 和 `batchSize` 两个 Attribute。在批量大小 RPC 设置它之前，批量大小是 10。

示例用打印来模拟处理每一批。每次已提交的 `GoTo` 都把位置推进到已处理范围之后，所以修改批量大小不会跳过或重复某个范围。重试的 `Execute` 可能再次处理同一个范围。因此真实的处理必须按每条记录的业务 ID 保持幂等。

批量大小 RPC 拒绝小于 1 或大于 1000 的值。停止 RPC 写入 `stopRequested`。循环随后在下一批开始前 graceful complete。循环停下后，Flow 完成。

RPC 写入控制值：

**Python**

```python
@rpc
def set_batch_size(self, context: Context, size: int) -> None:
    """Changes how many records each later batch processes."""
    if size < 1 or size > MAX_BATCH_SIZE:
        raise ValueError(f"batch size must be between 1 and {MAX_BATCH_SIZE}")
    BATCH_SIZE.set(context, size)

@rpc
def request_stop(self, context: Context) -> None:
    """Asks the loop to stop before its next batch."""
    STOP_REQUESTED.set(context, True)
```

例子: [examples/python/dex_examples/patterns/control-long-running-work/record_backfill_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/control-long-running-work/record_backfill_flow.py)

循环 Step 在每次 `Execute` 开始时读取控制值：

**Python**

```python
class ProcessRecordBatch(Step[BackfillProgress]):
    def wait_for(self, context: Context, progress: BackfillProgress) -> Wait:
        return Wait.until(Timer.by_duration(BATCH_INTERVAL))

    def execute(self, context: Context, progress: BackfillProgress) -> StepDecision:
        if STOP_REQUESTED.get(context):
            return graceful_complete(f"stopped before record {progress.next_record}")
        # An unset int Attribute reads as 0, and a set batch size is at least 1.
        size = BATCH_SIZE.get(context) or DEFAULT_BATCH_SIZE
        last = min(progress.next_record + size - 1, progress.last_record)
        print(f"processing records {progress.next_record} to {last}")
        if last == progress.last_record:
            return graceful_complete(f"processed {last} records")
        return go_to(ProcessRecordBatch, BackfillProgress(last + 1, progress.last_record))
```

例子: [examples/python/dex_examples/patterns/control-long-running-work/record_backfill_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/control-long-running-work/record_backfill_flow.py)

开始 Step、HTTP controller 和测试都在示例目录里。可以在 [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground) 里运行这个 HTTP 示例。

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

## 下一步

- [响应式更新](https://docs.superdurable.io/zh-Hans/design-patterns/responsive-update.md)
- [持久化定时器](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer.md)
