Skip to main content

Cron schedule

View as Markdown

A 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.

  1. Validation checks that the interval and the run count are positive.
  2. 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.
  3. 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.

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),
),
)

Example: examples/python/dex_examples/patterns/cron/cron_schedule_flow.py

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.

Next