---
title: "Cron 定时调度"
description: "Cron 定时调度在一个持久化 Flow 里按固定间隔、固定次数执行同一项工作。适合还需要手动\"立即运行\"或\"跳过一次\"的周期性工作。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/cron-schedule/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/durable-timer/cron.mdx"
locale: "zh-Hans"
language: "python"
---

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

# Cron 定时调度

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

Cron 定时调度在一个持久化 Flow 里按固定间隔、固定次数执行同一项工作。适合还需要手动"立即运行"或"跳过一次"的周期性工作。

**Flow 图：CronScheduleFlow**

**Step 列表**

1. `_Start`（起始 Step）：Validate the schedule and start waiting for the first run. 下一步：Flow 失败，或 `_WaitForSchedule`。
2. `_Run`：Record one scheduled run. 下一步：Flow 完成，或 这个分支结束。
3. `_WaitForSchedule`：Wait for the interval, a manual trigger, or a skip, then start a run. 下一步：`_Run`，或 `_WaitForSchedule`（再次）。 读取 `cron-schedule-skip`。

**RPC 列表**

- `trigger_now`：发布到 `cron-schedule-trigger`。

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

<a id="how-it-works"></a>

## 工作方式

调度按固定间隔计时，不按日历时间。

1. **Validation** 检查间隔和运行次数都是正数。
2. **Schedule** 等待间隔 Timer、trigger 消息或 skip 消息。一次 skip 用掉一个调度周期，但不执行工作。它启动下一个间隔；如果跳过的是最后一次，就优雅完成 Flow。Timer 或 trigger 会启动 **Run**；如果这不是最后一次，同一个 decision 还会启动下一次 **Schedule**。
3. **Run** 执行计划中的工作。最后一次运行完成 Flow；其他每次运行以 dead end 结束自己的分支。

要立即运行，用 Client 向 trigger Channel 发布消息。Go、Python 和 TypeScript 示例还把这一步包装成 `TriggerNow` RPC。要跳过下一次，向 skip Channel 发布消息。

<a id="code"></a>

## 核心实现

注意 `AnyOf` 等待，以及同时启动本次运行和下一次等待的 `GoToMany`。

**Python**

```python
class _WaitForSchedule(Step[_ScheduleState]):
    def __init__(
        self,
        trigger: Channel[None],
        skip: Channel[None],
    ) -> None:
        self.trigger = trigger
        self.skip = skip

    def wait_for(self, context: Context, state: _ScheduleState) -> Wait:
        return Wait.any_of(
            Timer.by_duration(state.interval.duration()),
            self.trigger.for_one(),
            self.skip.for_one(),
        )

    def execute(self, context: Context, state: _ScheduleState) -> StepDecision:
        if self.skip.results(context):
            return self._next_schedule(state)
        run_input = _RunInput(
            run_number=state.remaining_runs,
            is_final=state.remaining_runs == 1,
        )
        if run_input.is_final:
            return go_to(_Run, run_input)
        return go_to_many(
            StepMovement.of(_Run, run_input),
            StepMovement.of(
                _WaitForSchedule,
                _ScheduleState(state.interval, state.remaining_runs - 1),
            ),
        )
```

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

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

## 规则和陷阱

- 在启动本次运行的同一个 decision 里启动下一次等待。这样运行慢了也不会推迟调度。
- 每次运行的外部副作用用它的 occurrence 作为键，例如 Flow ID 加运行序号。被中断的运行可能再执行一次，接收方用这个键丢弃重复。

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

## 下一步

- [提醒](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/reminder.md)
- [Channel](https://docs.superdurable.io/zh-Hans/concepts/primitives/channel.md)
- [Timer](https://docs.superdurable.io/zh-Hans/concepts/primitives/timer.md)
