Cron@rhythmjs/cron
Schedules and handlers
A job is a name, a schedule and handlers; the expression and time zone are checked when you register it, not when it first fires.
Schedules#
.cron(name, schedule, ...handlers) registers a job. schedule is a standard 5-field cron expression (minute, hour, day of month, month, day of week) or a nickname, exactly as Bun.cron accepts them:
import { RhythmCron } from "@rhythmjs/cron";
const cron = new RhythmCron()
.cron("poll", "*/5 * * * *", () => pollFeeds())
.cron("digest", "@hourly", () => sendDigest())
.cron("standup", "0 9 * * MON-FRI", () => remindTeam());Day and month names (MON-FRI) are understood, and the usual nicknames such as @hourly and @daily work. Autocomplete for them comes from Bun's CronWithAutocomplete type, which is what the schedule parameter uses.
Time zones#
By default a schedule runs in the system's time zone. Set tz (an IANA name) in the constructor to change it for every job, or pass an object to give one job its own:
const cron = new RhythmCron({ tz: "UTC" })
.cron("cleanup", "0 3 * * *", () => cleanup()) // 03:00 UTC
.cron("report", { schedule: "30 9 * * MON-FRI", tz: "America/New_York" }, () => report());A job's own tz wins over the instance's. The resolved zone is what cron.jobs reports and what cron.next uses to preview the next fire.
Handlers#
Handlers are (ctx, next) functions, like route handlers. The context is whatever the app supplied (the I you gave RhythmCron<I>, filled in by startCron or by start(input)) plus ctx.job:
const cron = new RhythmCron<{ db: Db }>().cron("cleanup", "0 3 * * *", async (ctx) => {
console.log(`${ctx.job.name} fired at ${ctx.job.firedAt.toISOString()}`);
await ctx.db.deleteExpiredSessions();
});ctx.job holds name, schedule (the expression), tz (undefined when the system zone is used) and firedAt, a Date. A job may have several handlers; they run in order, and each continues the chain by calling next(). A run is done when the chain settles.
A job never overlaps itself: Bun computes the next fire after the run settles. A handler that outlasts its interval skips the fires it covered rather than stacking runs.
Extension middleware [#extension]
As with routes, the first handler may be extension middleware such as derive(...). It widens the context for the handlers after it:
import { derive } from "@rhythmjs/rhythm";
const cron = new RhythmCron<{ db: Db }>().cron(
"expire",
"0 * * * *",
derive((ctx) => ({ cutoff: new Date(Date.now() - 24 * 60 * 60 * 1000) })),
async (ctx) => {
await ctx.db.deleteSessionsBefore(ctx.cutoff);
},
);To widen the context for every job instead, put the extension middleware in cron.use(...); the returned instance carries the new fields in its types.
Validation at registration#
Mistakes surface when the job is added, in the file where you wrote it, not the first time the schedule would have fired:
- A malformed expression or unknown time zone throws from
.cron()(the check is Bun's own parser). - A schedule that can never match, such as
"0 0 30 2 *"(February 30), throws aTypeError:cron job "name": "0 0 30 2 *" never fires. - A duplicate name throws a
TypeError:cron job "name" is already registered.
Names#
A job's name is its identity. It labels logs and errors, appears in ctx.job.name, and is the key for run and next. Names are unique per instance; reuse across separate RhythmCron instances is fine, but choose stable, descriptive names ("cleanup", "billing:invoices") since status pages and locks usually key on them. cron.jobs lists every registered job as { name, schedule, tz }.