跳到主要内容

Cron 定时调度

查看 Markdown

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

工作方式

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

  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 发布消息。

核心实现

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

cron_schedule_flow.pyPython
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

规则和陷阱

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

下一步