Cron schedule
View as MarkdownA cron schedule runs the same work at a fixed interval, a set number of times, in one durable Flow. Use it for recurring work that also needs a manual run now or a skipped occurrence.
How it works
The schedule counts a fixed interval, not calendar times.
- Validation checks that the interval and the run count are positive.
- Schedule waits for the interval Timer, a trigger message, or a skip message. A skip uses up one occurrence without running the work. It starts the next interval, or completes the Flow gracefully when it skips the last occurrence. The Timer or a trigger starts Run and, unless this is the last occurrence, the next Schedule in the same decision.
- Run does the scheduled work. The last run completes the Flow; every other run ends its branch with a dead end.
To run the work now, publish to the trigger Channel with the Client. The Go, Python, and TypeScript examples also wrap this in a TriggerNow RPC. To skip the next occurrence, publish to the skip Channel.
Core implementation
Notice the AnyOf wait and the GoToMany that starts the run and the next wait together.
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),
),
)
Example: 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)));
}
}
Example: 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,
}),
);
}
}
Example: 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,
},
),
]))
}
}
Rules and pitfalls
- Start the next wait in the same decision as the run. A slow run then does not shift the schedule.
- Key each run's external effect by its occurrence, such as the Flow ID and the run number. A run that was cut off can run again, and the receiver uses the key to drop the duplicate.