Cron@rhythmjs/cron
Lifecycle and errors
Start with the app, stop with the app; a failing run goes to onError and the job keeps its schedule. Jobs are in-process, so plan for restarts and replicas.
On this page
Starting and stopping#
The usual way is startCron, registered on the app:
const app = new Rhythm().register(decorate(() => ({ db: openDb() }))).register(startCron(cron));
await app.callback()(); // jobs scheduled with the app's startup context
await app.stop(); // jobs cancelledstartCron(cron) starts the jobs with the startup context and registers a cleanup that stops them, so shutdown needs no extra code. Without an app, the same thing is available by hand:
cron.start(input?)#- Schedules every job with
Bun.cron, usinginputas the context. Starting a running instance is a no-op. Returns the instance. cron.stop()#- Cancels every scheduled job. The same instance can be started again.
cron.running#truewhile jobs are scheduled.Symbol.dispose#RhythmCronisDisposable, sousing cron = new RhythmCron()...stops it at the end of the scope.
cron.callback() is start in the Mountable shape, which is how an app hands it its input. Cron is not request middleware, so use startCron rather than mount.
By default scheduled jobs keep the process alive, like any timer. Pass unref: true to let the process exit while jobs are scheduled; useful for scripts and tests.
Running a job now#
cron.run(name, input?) runs a job's whole pipeline immediately, middleware first, outside its schedule. It is the manual trigger for an HTTP route or a test, and it resolves with the context the run used:
const api = new RhythmRouter().post("/jobs/:name/run", async (ctx) => {
await cron.run(ctx.params.name, { db });
json(ctx, { ok: true });
});Without input, run uses the input the instance was started with. An unknown name throws a RangeError. Errors reject here, to the caller, rather than going to onError.
cron.next(name, from?) returns the next fire as a Date in the job's time zone, or null if it never fires again:
cron.next("report"); // next 09:30 on a weekday in New YorkErrors#
Bun's in-process cron behaves like setTimeout: an uncaught throw or rejection reaches uncaughtException or unhandledRejection and, with no listener, ends the process. RhythmCron catches runs itself and passes the error and its context to onError. The default logs cron job "name" failed with console.error. Either way the job stays scheduled and fires again at its next match.
const cron = new RhythmCron({
onError(error, ctx) {
console.error(`${ctx.job.name} failed at ${ctx.job.firedAt.toISOString()}`, error);
},
});onError is a good place to report to your error tracker. If you want a failed run to take the process down, throw from onError yourself.
In-process, not durable#
These jobs live and die with the process, like Bun.cron(schedule, handler) itself:
- A run missed while the process was down is not replayed.
- Nothing is stored: there is no history, retry queue or backlog. If a job must be retried, do it in the handler or let the next fire pick up the work (make jobs idempotent and query for "what is due").
- Under
bun --hot, Bun stops in-process jobs before reloading, and the re-evaluated module registers them again.
For work that must survive restarts or be distributed over workers, you need a durable queue; this package deliberately has none.
Several replicas#
Every replica of your app fires every job. When only one should run, take a lock in use(), so it guards every job and the losers skip the handlers by not calling next():
const cron = new RhythmCron<{ redis: Redis }>().use(async (ctx, next) => {
const slot = `lock:${ctx.job.name}:${ctx.job.firedAt.toISOString().slice(0, 16)}`;
if (await ctx.redis.set(slot, "1", "EX", 300, "NX")) await next();
});A Redis SET NX or a unique database row both work. Key the lock on the job and the fire time so each tick is claimed once.
No overlap#
A job never runs concurrently with itself in one process: the next fire is computed after the current run settles. Different jobs do run independently. Across replicas the lock above is what prevents duplicates.
Testing without waiting#
Nothing needs a real minute to pass.
Call run to execute a job through its middleware and handlers, and next to check a schedule:
import { expect, test } from "bun:test";
test("cleanup deletes expired sessions", async () => {
const db = { deleteExpiredSessions: mock(async () => 3) };
await cron.run("cleanup", { db });
expect(db.deleteExpiredSessions).toHaveBeenCalled();
expect(cron.next("cleanup", new Date("2026-01-01T00:00:00Z"))?.toISOString()).toBe("2026-01-01T03:00:00.000Z");
});To check what start schedules and to fire the handlers yourself, replace Bun.cron with spyOn(Bun, "cron"); its mock receives the expression, the handler and { tz }, and calling the handler is a fire:
import { spyOn } from "bun:test";
const spy = spyOn(Bun, "cron").mockImplementation(((schedule, handler) => {
fired.push({ schedule, handler });
return { stop() {}, ref() {}, unref() {}, [Symbol.dispose]() {} };
}) as never);
cron.start({ db });
await fired[0].handler(); // runs middleware and handlers, errors go to onError
spy.mockRestore();