Scheduling
Recurring workflows with ScheduledWorkflow — fixed intervals via everyMs or DST-aware cron via cron + timezone — fired each tick by the NestJS module's schedules option, started exactly once per window by an idempotent time-bucket run id.
A scheduled workflow is just a normal workflow that the engine starts on a recurring cadence for
you — a nightly report, an hourly sync, a cleanup every five minutes. You describe the cadence with a
ScheduledWorkflow, hand it to the module's schedules option, and the engine fires it each tick.
The interesting part is the exactly-once guarantee: even with several instances racing on the
same tick, each schedule window starts exactly once.
These are code-registered schedules, fixed at deploy time. For schedules created and managed at runtime (one per user, per tenant, per automation) see Persisted schedules.
Describing a schedule — ScheduledWorkflow
interface ScheduledWorkflow<W extends WorkflowRef = WorkflowRef> {
/** Stable key identifying this schedule — part of the deterministic run id. */
key: string;
/** The workflow to start: a `@Workflow` class, or a registered name. */
workflow: W;
/** The input every run starts with — typed against `run` when `workflow` is a class. */
input?: WorkflowInputOf<W>;
/** Start one run every `everyMs`. Mutually exclusive with `cron`. */
everyMs?: number;
/** A cron expression evaluated in `timezone`. Mutually exclusive with `everyMs`. */
cron?: string;
/** IANA timezone the `cron` fires in (e.g. `America/Sao_Paulo`). Defaults to UTC. */
timezone?: string;
/** Temporarily stop firing this schedule (kept registered). Defaults to false. */
paused?: boolean;
/** What to do when an earlier window's run hasn't finished (interval and cron alike): `'allow'`
* (default) starts the new window anyway; `'skip'` skips every window while any earlier run of
* this schedule is still in flight. */
overlap?: 'allow' | 'skip';
/** Randomly delay dispatch by up to this many ms, to spread load across instances ticking the
* same boundary. Opt-in; absent = fire immediately. */
jitter?: number;
/** Enqueue windows missed while the scheduler was down, instead of silently skipping them.
* `maxCatchup` bounds how many prior windows are backfilled. Opt-in; absent = only the current
* window fires. */
backfill?: { maxCatchup: number };
/** Stamp the runs with this namespace instead of the firing instance's own. */
namespace?: string;
}Every schedule has a stable key, the workflow to start, and an optional input. The cadence is
either everyMs (a fixed interval) or cron + timezone (a calendar expression) — they are
mutually exclusive. The rest of the fields tune what happens around a fire: paused to stop it
temporarily, overlap to guard against pile-up, jitter to spread load, and backfill to catch up
on windows missed during downtime — each covered below.
Wiring it up — the schedules option
Declare your schedules once, in their own file, and pass them to DurableModule. The durable-timer
poller fires them on every driving instance (any instance without drive: false), once on boot and
then every timerPollMs (default 1s):
import type { ScheduledWorkflow } from '@dudousxd/nestjs-durable';
import { CacheSyncWorkflow } from './cache/cache-sync.workflow';
import { DailyReportWorkflow } from './reports/daily-report.workflow';
// Run DailyReportWorkflow at 02:00 in São Paulo — DST-aware.
export const dailyReport: ScheduledWorkflow<typeof DailyReportWorkflow> = {
key: 'daily-report',
workflow: DailyReportWorkflow,
input: { recipients: ['ops@example.com'] },
cron: '0 2 * * *',
timezone: 'America/Sao_Paulo',
};
// Run CacheSyncWorkflow every five minutes.
export const cacheSync: ScheduledWorkflow = {
key: 'cache-sync',
workflow: CacheSyncWorkflow,
everyMs: 5 * 60 * 1000,
};
export const SCHEDULES = [dailyReport, cacheSync];import { DurableModule } from '@dudousxd/nestjs-durable';
import { SCHEDULES } from './schedules';
@Module({
imports: [DurableModule.forRoot({ store, transport, schedules: SCHEDULES })],
providers: [DailyReportWorkflow, CacheSyncWorkflow],
})
export class AppModule {}Keeping each schedule in an exported constant pays off later: the same object is what you pass to look up a window's run or to fire the schedules yourself.
Because schedules is module configuration, it can depend on the environment like any other option.
With forRootAsync, for example, pause the nightly report everywhere but production:
DurableModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
store,
transport,
schedules: [
{ ...dailyReport, paused: config.get('NODE_ENV') !== 'production' },
cacheSync,
],
}),
});Each schedule's workflow is the @Workflow class it starts, the same reference ctx.child and
engine.start take. Annotating the schedule as ScheduledWorkflow<typeof DailyReportWorkflow> checks
input against the class's run, so a schedule can't drift from the workflow it starts; the plain
ScheduledWorkflow accepts any input. A class that isn't decorated with @Workflow stops the app from
booting, instead of failing on its first fire. For a workflow that runs in another runtime (a Python
worker, say), pass its registered name as a string instead.
There's no schedule option on @Workflow itself — schedules are deployment config (which cadence runs
where), kept separate from the workflow definition, so the same workflow can be scheduled differently
per environment or started ad-hoc. The daily-report schedule above starts this ordinary provider:
@Workflow({ name: 'daily-report', version: '1' })
export class DailyReportWorkflow {
constructor(private readonly reports: ReportService) {}
async run(ctx: WorkflowCtx, input: { recipients: string[] }) {
const rows = await ctx.step(this.reports.gatherYesterday, undefined);
await ctx.step(this.reports.email, { rows, to: input.recipients });
return { rows: rows.length };
}
}The workflow body itself is ordinary — it doesn't know it's scheduled. The engine starts it on the cadence; from there it's just steps that checkpoint and resume like any other run:
1@Workflow({ name: 'daily-report', version: '1' })2export class DailyReportWorkflow {3 constructor(private readonly reports: ReportService) {}4 async run(ctx: WorkflowCtx) {5 const rows = await ctx.step(this.reports.gatherYesterday, undefined);6 await ctx.step(this.reports.email, rows);7 return { rows: rows.length };8 }9}Fixed intervals — everyMs
everyMs starts one run every interval. The current window is identified by the time bucket
floor(now / everyMs), which becomes part of the run id (sched:<key>:<bucket>). Every tick inside
the same window resolves to the same run id, so re-firing the schedule within a window is a no-op.
{ key: 'cache-sync', workflow: CacheSyncWorkflow, everyMs: 5 * 60 * 1000 } // every 5 minutesUse a fixed interval when "roughly every N" is what you want and you don't care about wall-clock alignment to the calendar.
Cron — cron + timezone
For calendar-aligned schedules, use a cron expression evaluated in an IANA timezone. The expression
is the standard 5 fields (m h dom mon dow), or 6 with a leading seconds field. Because it is
evaluated in the named timezone, it is DST-aware — 0 2 * * * in America/Sao_Paulo fires at
02:00 local regardless of daylight-saving shifts, not at a fixed UTC offset.
{ key: 'nightly-report', workflow: DailyReportWorkflow, cron: '0 2 * * *', timezone: 'America/Sao_Paulo' }The window for a cron schedule is its most recent fire time at or before now — the deterministic
"bucket" the run is keyed on (sched:<key>:<prevFireMs>). Polling repeatedly between two fires
resolves to the same bucket, and thus the same run id, so the run for a given fire starts once.
Cron needs the optional peer dependency cron-parser — core stays dependency-free, and only users
who schedule by cron pull it in. Install it where you run the engine:
npm i cron-parserOmitting it and using a cron schedule throws a clear error pointing you to install it.
Pausing a schedule — paused
Set paused: true to stop a schedule from firing without removing it from your config. It stays
registered — the dashboard still lists it, and un-pausing it later just resumes ticking — but the
poller skips it entirely on every tick while paused:
{ key: 'nightly-report', workflow: DailyReportWorkflow, cron: '0 2 * * *', paused: true }Skipping overlapping runs — overlap
By default (overlap: 'allow'), a schedule starts every window on schedule even if an earlier
window's run is still going — a slow run and a fresh one can end up in flight together. Set
overlap: 'skip' to start no window while any earlier run of the schedule is still in flight
(pending, running, suspended, blocked or cancelling):
{ key: 'cache-sync', workflow: CacheSyncWorkflow, everyMs: 60_000, overlap: 'skip' }Every window that comes due in the meantime is skipped, and the schedule fires again at the first
window after that run finishes. It works the same for everyMs and cron schedules, sees runs
started before a restart or by another instance, and with backfill starts missed windows one at a
time.
Dispatch jitter — jitter
When many instances tick on the same boundary, they all try to start the same window at once. jitter
randomly delays the dispatch by up to that many ms before firing, spreading the load instead of every
instance hitting the store in the same instant:
{ key: 'cache-sync', workflow: CacheSyncWorkflow, everyMs: 60_000, jitter: 5_000 } // fire within 5s of the tickJitter only delays when an instance attempts the dispatch — it does not change the run id (still the time bucket), so idempotency is unchanged: however many instances jitter the same window, it still starts exactly once.
An instance never waits the jitter out inside a tick. A due window gets its own fire time, up to
jitter after the instance first saw it, and a later tick starts it once that time arrives; a window
deferred past the end of its interval still fires. Meanwhile other schedules and the rest of the poll
(due timers, retries, timeouts) carry on, even when several jittered windows come due together, as
after a restart. Once an instance has seen the window's run exist — it started it, or another instance
did — later ticks in that window skip the schedule without a store read.
Pinning the pool — namespace
The instance that wins the race to fire a window decides which namespace the run is stamped with: its own. When the workflow can only run in one pool — its steps need a capability only that pool's workers have — pin the namespace on the schedule, so the run lands there whichever instance fires it:
{ key: 'render-thumbnails', workflow: RenderThumbnailsWorkflow, everyMs: 60_000, namespace: 'gpu' }Catching up on missed windows — backfill
If the process running the poller is down when a window would have fired, that window is missed —
by default, only the current window fires the next time the poller runs. Set backfill to enqueue
the windows that were missed instead:
{ key: 'hourly-rollup', workflow: HourlyRollupWorkflow, everyMs: 60 * 60 * 1000, backfill: { maxCatchup: 6 } }maxCatchup bounds how many prior windows are backfilled, so a long outage can't flood the system
with a backlog — at most maxCatchup missed windows start, oldest first, followed by the current one.
Backfilled runs use each missed window's own deterministic bucket run id, so if some of them already
ran (e.g. another instance caught up first), engine.start's idempotency skips those and only the
genuinely-missing ones start.
Putting it together
The four options compose — a schedule that skips pile-up, spreads load, and catches up after downtime:
{
key: 'hourly-rollup',
workflow: HourlyRollupWorkflow,
everyMs: 60 * 60 * 1000,
overlap: 'skip', // don't pile up if a rollup runs long
jitter: 10_000, // spread dispatch across instances ticking the same hour
backfill: { maxCatchup: 6 }, // catch up on up to 6 hours missed while the poller was down
}On a tenant
A tenant (connection, no store) cannot fire schedules itself. Its workers announce them, and the
control plane adopts them as persisted schedules, fires them, and shows them on its console. See
Schedules on a tenant.
Exactly-once across instances
The guarantee that makes scheduling safe in a multi-instance deployment is the idempotent
time-bucket run id. Each window — a fixed-interval index, or a cron fire time — maps to a
deterministic run id, and engine.start is idempotent by run id: starting the same id twice is a
no-op. So when several driving instances tick at the same moment and all try to start the current
window, they all compute the same run id and only the first actually creates the run. Each instance
also remembers the windows whose run it has seen exist, so a window that already fired costs no store
read on the ticks after that. The poller fires
schedules on driving instances only, so a dashboard-only instance (drive: false) never starts them.
The mechanism is the same one used everywhere durability needs idempotency — see Workflows & steps for how a deterministic run id underpins exactly-once starts in general. The result for scheduling: each window starts exactly once, no matter how many instances are racing the tick or how often the poller fires.
Looking up a schedule's run
Each window's run id is deterministic, so any provider can find the run a schedule started — no
bookkeeping table needed. Inject WorkflowEngine and pass the schedule to scheduleRunIdAt, which
computes the id of its window at a given time (sched:<key>:<bucket>):
import { Controller, Get } from '@nestjs/common';
import { WorkflowEngine, scheduleRunIdAt } from '@dudousxd/nestjs-durable';
import { dailyReport } from '../schedules';
@Controller('reports')
export class ReportsController {
constructor(private readonly engine: WorkflowEngine) {}
/** Did the most recent 02:00 report run, and how did it end? */
@Get('daily/latest')
async latestDaily() {
const run = await this.engine.getRun(scheduleRunIdAt(dailyReport, Date.now()));
return run ? { status: run.status, output: run.output } : { status: 'not started' };
}
}getRun returns null when the window hasn't fired yet — for instance between 02:00 and the next
poller tick, or while the schedule is paused. Passing the same dailyReport object the module was
given keeps the key, the cron expression and the timezone in one place. The two pieces the id is built
from are exported too, for when all you have is the raw values: scheduledRunId(key, everyMs, nowMs)
for a fixed interval, and prevCronFireMs(expr, nowMs, timezone?) for the cron fire time a window is
keyed on.
Firing schedules from your own trigger
The module's poller is the usual way to fire schedules, but it only runs on driving instances. If your
deployment fires scheduled work from outside — a Kubernetes CronJob, Cloud Scheduler, EventBridge, a
serverless function — leave schedules off the module and call runSchedules from that trigger. It does
what the poller does on each tick: fires every schedule's current window (applying
paused/overlap/jitter/backfill) and returns the run ids it started.
The trigger only needs to enqueue the runs, so boot a standalone application context as a
producer-only process (drive: false, consumers: false):
it executes nothing itself, and a driving instance picks the new runs up on its next poll.
import { NestFactory } from '@nestjs/core';
import { WorkflowEngine, runSchedules } from '@dudousxd/nestjs-durable';
import { SchedulerModule } from './scheduler.module'; // imports DurableModule with drive: false, consumers: false
import { SCHEDULES } from './schedules';
async function main() {
const app = await NestFactory.createApplicationContext(SchedulerModule);
const started = await runSchedules(app.get(WorkflowEngine), SCHEDULES, Date.now());
console.log(`started ${started.length} scheduled run(s)`);
await app.close();
}
void main();Every guarantee on this page still holds — the run id is the window's bucket, so a trigger that fires
twice, or fires alongside a driving instance that also has schedules, still starts each window once.
Run the trigger at least as often as your finest schedule, since a call only starts the windows current
at Date.now() (plus whatever backfill catches up).
Testing a schedule
In a test, call runSchedules against the engine of your TestingModule with a fixed clock, so you
choose which window fires. Its fourth argument overrides the random that draws each window's
jitter delay (Math.random by default); random: () => 0 makes a jittered schedule fire in the
same call. Pass the same engine on every call: fired windows and deferred jittered windows are
remembered per engine object.
const engine = moduleRef.get(WorkflowEngine);
const at = Date.parse('2026-03-01T05:00:00Z'); // 02:00 in São Paulo
const [runId] = await runSchedules(engine, [dailyReport], at, {
random: () => 0,
});
expect(runId).toBe(scheduleRunIdAt(dailyReport, at));
expect((await engine.waitForRun(runId)).status).toBe('completed');Leave schedules off the module under test. The poller fires them once at boot even with
timerPollMs: 0 (which only stops the interval), on the real clock, before your test picks a window.
Versioning & determinism
Keeping in-flight runs replay-safe across code changes — workflow versions for breaking changes, the NonDeterminismError guard, the deterministic now/random/uuid sources, and ctx.patched for guarding an in-place change without a new version.
Persisted schedules
engine.schedules — Temporal-style schedules created, updated, paused, resumed, triggered and deleted at runtime, persisted in the store (durable_schedules), fired by every driving engine's timer poll with cron + timezone or fixed intervals, jitter, overlap and catch-up policies. Safe with any number of workers.