Cron 定时调度
查看 MarkdownCron 定时调度在一个持久化 Flow 里按固定间隔、固定次数执行同一项工作。适合还需要手动"立即运行"或"跳过一次"的周期性工作。
工作方式
调度按固定间隔计时,不按日历时间。
- Validation 检查间隔和运行次数都是正数。
- Schedule 等待间隔 Timer、trigger 消息或 skip 消息。一次 skip 用掉一个调度周期,但不执行工作。它启动下一个间隔;如果跳过的是最后一次,就优雅完成 Flow。Timer 或 trigger 会启动 Run;如果这不是最后一次,同一个 decision 还会启动下一次 Schedule。
- Run 执行计划中的工作。最后一次运行完成 Flow;其他每次运行以 dead end 结束自己的分支。
要立即运行,用 Client 向 trigger Channel 发布消息。Go、Python 和 TypeScript 示例还把这一步包装成 TriggerNow RPC。要跳过下一次,向 skip Channel 发布消息。
核心实现
注意 AnyOf 等待,以及同时启动本次运行和下一次等待的 GoToMany。
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
type waitForCronSchedule struct {
dex.StepDefaults
}
func (waitForCronSchedule) WaitFor(
_ dex.Context,
state cronScheduleState,
) (*dex.Wait, error) {
return dex.AnyOf(
dex.Timer(state.Interval.Duration()),
Trigger.ForOne(),
Skip.ForOne(),
), nil
}
func (waitForCronSchedule) Execute(
ctx dex.Context,
state cronScheduleState,
) (*dex.StepDecision, error) {
skipResults, err := Skip.GetConditionResults(ctx)
if err != nil {
return nil, err
}
if len(skipResults) > 0 {
return nextCronSchedule(state), nil
}
run := cronScheduleRun{
RunNumber: state.RemainingRuns,
IsFinal: state.RemainingRuns == 1,
}
if run.IsFinal {
return dex.GoTo(runCronSchedule{}, run), nil
}
state.RemainingRuns--
return dex.GoToMany(
dex.MovementOf(runCronSchedule{}, run),
dex.MovementOf(waitForCronSchedule{}, state),
), nil
}
final class WaitForSchedule implements Step<ScheduleState> {
@Override
public Wait waitFor(final Context context, final ScheduleState state) {
return Wait.anyOf(
Timer.byDuration(state.interval.duration()),
trigger.forOne(),
skip.forOne());
}
@Override
public StepDecision execute(final Context context, final ScheduleState state) {
if (!skip.getConditionResults(context).isEmpty()) {
return nextSchedule(state);
}
final RunInput runInput = new RunInput(state.remainingRuns, state.remainingRuns == 1);
if (runInput.isFinal) {
return StepDecision.goTo(Run.class, runInput);
}
return StepDecision.goToMany(
StepMovement.of(Run.class, runInput),
StepMovement.of(
WaitForSchedule.class,
new ScheduleState(state.interval, state.remainingRuns - 1)));
}
}
例子: examples/java/src/main/java/io/superdurable/dex/patterns/cron/CronScheduleFlow.java
class WaitForSchedule implements Step<ScheduleState> {
public readonly inputCodec = scheduleStateCodec;
public constructor(
private readonly trigger: Channel<void>,
private readonly skip: Channel<void>,
private readonly run: Run,
) {}
public waitFor(_context: Context, state: ScheduleState): Wait {
return Wait.anyOf(
Timer.byDuration(intervalMs(state.interval)),
this.trigger.forOne(),
this.skip.forOne(),
);
}
public execute(context: Context, state: ScheduleState): StepDecision {
if (this.skip.results(context).length > 0) {
return this.nextSchedule(state);
}
const input: RunInput = {
runNumber: state.remainingRuns,
isFinal: state.remainingRuns === 1,
};
if (input.isFinal) {
return goTo(Run, input);
}
return goToMany(
StepMovement.of(Run, input),
StepMovement.of(WaitForSchedule, {
interval: state.interval,
remainingRuns: state.remainingRuns - 1,
}),
);
}
}
例子: examples/typescript/src/patterns/cron/cron-schedule-flow.ts
#[derive(Default)]
struct WaitForSchedule;
impl Step for WaitForSchedule {
type Input = ScheduleState;
fn wait_for(&self, _context: &mut Context, state: Self::Input) -> HandlerResult<Wait> {
Ok(Wait::any_of([
Timer::by_duration(state.interval.duration()),
TRIGGER.for_one(),
SKIP.for_one(),
]))
}
fn execute(&self, context: &mut Context, state: Self::Input) -> HandlerResult<StepDecision> {
if !SKIP.condition_results(context)?.is_empty() {
return Ok(next_schedule(state));
}
let run_input = RunInput {
run_number: state.remaining_runs,
is_final: state.remaining_runs == 1,
};
if run_input.is_final {
return Ok(StepDecision::go_to(&Run, run_input));
}
Ok(StepDecision::go_to_many([
StepMovement::to(&Run, run_input),
StepMovement::to(
&WaitForSchedule,
ScheduleState {
interval: state.interval,
remaining_runs: state.remaining_runs - 1,
},
),
]))
}
}
规则和陷阱
- 在启动本次运行的同一个 decision 里启动下一次等待。这样运行慢了也不会推迟调度。
- 每次运行的外部副作用用它的 occurrence 作为键,例如 Flow ID 加运行序号。被中断的运行可能再执行一次,接收方用这个键丢弃重复。