Cron Trigger
Schedule workflows with cron expressions and leader election
Cron Trigger
The Cron trigger allows you to schedule workflows to run at specific times using standard cron expressions. It features built-in leader election to ensure that only one instance of your application runs the schedule in a multi-instance deployment.
Installation
pnpm add @stepflowjs/trigger-cronUsage
import { CronTrigger } from "@stepflowjs/trigger-cron";
const trigger = new CronTrigger(
{
expression: "0 * * * *", // Every hour
timezone: "America/New_York",
catchUp: true,
},
storage, // Storage adapter for leader election
"daily-report", // Unique ID for this schedule
);
await trigger.start(async (event) => {
console.log("Cron fired at:", event.data.scheduledTime);
await stepflow.trigger("daily-report", event.data);
});Leader Election
When running multiple instances of your application, you don't want every instance to trigger the same cron job. CronTrigger uses your Stepflow storage adapter to perform leader election. Only the "leader" instance will execute the trigger handler.
If the leader instance goes down, another instance will automatically take over as the leader.
Catch-up Runs
If catchUp is set to true, the trigger will check for any missed executions when it starts (or when an instance becomes the leader). This is useful for ensuring that jobs run even if the system was down during the scheduled time.
Configuration
| Option | Type | Default | Description |
|---|---|---|---|
expression | string | required | Cron expression (e.g., 0 * * * *) |
timezone | string | UTC | IANA timezone |
catchUp | boolean | false | Run missed executions on startup |
Event Data
The event data passed to the handler contains:
{
scheduledTime: string; // ISO timestamp of the scheduled time
timezone: string; // The timezone used for the schedule
}