do-jobs
v0.2.0
Published
Type-safe delayed and interval jobs for Cloudflare Durable Objects.
Readme
do-jobs
Type-safe delayed and interval jobs for Cloudflare Durable Objects.
Getting Started
1. Install
pnpm add do-jobs zoddo-jobs validates job payloads with the Standard Schema interface, so you can use libraries like Zod.
The Durable Object class must use SQLite storage (new_sqlite_classes in wrangler, or storage: "sqlite").
2. Define jobs and wire your Durable Object
import { createDefineJob, setupJobs, type JobRuntime } from "do-jobs";
import { z } from "zod";
type Env = {
WEBHOOK_URL: string;
};
const defineJob = createDefineJob<{ env: Env }>();
const sendWebhook = defineJob({ type: "send-webhook" })
.input(
z.object({
message: z.string().min(1),
}),
)
.handler(async ({ input, context, job }) => {
await fetch(context.env.WEBHOOK_URL, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ id: job.id, message: input.message }),
});
});
const jobs = [sendWebhook] as const;
export class JobsDO extends DurableObject<Env> {
private runtimePromise: Promise<JobRuntime<typeof jobs>>;
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
this.runtimePromise = setupJobs({
ctx,
context: { env },
jobs,
});
}
async fetch(request: Request): Promise<Response> {
const runtime = await this.runtimePromise;
const url = new URL(request.url);
if (url.pathname === "/enqueue") {
await runtime.schedule(sendWebhook, {
input: { message: "hello" },
at: Date.now() + 5_000,
});
return new Response("queued", { status: 202 });
}
return new Response("not found", { status: 404 });
}
async alarm(): Promise<void> {
const runtime = await this.runtimePromise;
await runtime.onAlarm();
}
}Docs
createDefineJob<TContext>()
Creates a typed builder for declaring jobs.
const defineJob = createDefineJob<{ env: Env }>();A job definition requires:
type: unique string identifier.input(schema): any Standard Schema compatible validator.handler(({ input, context, job }) => ...): execution function.
setupJobs({ jobs, ctx, context, maxJobsPerAlarm?, maxFailedJobsPerType? })
Initializes runtime state and returns a JobRuntime.
jobs: list of registered job definitions.ctx: Durable Object state.context: object injected into every handler.maxJobsPerAlarm(default50): upper bound of jobs executed per alarm tick.maxFailedJobsPerType(default100): number of newest failed runs retained for each job type. Set it to0to retain none.
setupJobs(...) also:
- creates/migrates internal SQLite tables,
- restores the Durable Object alarm from the database if none is currently scheduled.
JobRuntime
setupJobs(...) returns methods:
onAlarm(): run due jobs and schedule the next alarm.setNextAlarm(): force recalculation of next alarm time.schedule(job, { input, at }): queue a one-off run.scheduleInterval(job, { input, dedupeKey, everyMs, startAt? }): create/update an interval schedule.everyMsmust be at least 5 seconds. Safe to call on every Durable Object boot — see the note below.cancelInterval(job, { dedupeKey }): cancel a previously scheduled interval and delete any still-queued runs from it.scheduleDebounced(job, { input, dedupeKey, delayMs, maxDelayMs? }): queue a run that collapses with other calls sharing the samededupeKey.cancelDebounced(job, { dedupeKey }): delete the pending debounced run, if there is one.
Debounced jobs
scheduleDebounced waits delayMs before running, and every further call for the same (job.type, dedupeKey) pushes that deadline out again. Call it with a 5 second delay, call it again 3 seconds later, and the job runs 5 seconds after the second call.
await runtime.scheduleDebounced(syncDocument, {
input: { documentId },
dedupeKey: `sync:${documentId}`,
delayMs: 5_000,
maxDelayMs: 30_000,
});Only queued runs collapse. Once a handler starts, a new call queues a separate run rather than waiting behind the one in flight.
The newest call's payload wins: collapsing replaces the stored input, so the handler always sees the most recent one.
Without maxDelayMs a steady stream of calls defers the run forever. maxDelayMs caps the total wait against the first call in the window, so the job runs even while calls keep arriving. It must be at least delayMs.
The returned record has a collapsed flag: true when the call folded into a pending run, false when it created one.
Behavior Notes
- Inputs are JSON-serialized and validated before enqueueing, then validated again before handler execution.
- Transforming schemas accept their input type when scheduling and pass their output type to handlers.
- Persisted payloads must remain valid after JSON serialization.
- Interval jobs are deduplicated by
(job.type, dedupeKey). Debounced jobs use the same key pair, but interval keys belong to schedules while debounce keys belong to runs, so an interval and a debounce can share a key without interfering. scheduleIntervalis idempotent w.r.t. timing: re-registering an unchanged, still-active schedule preserves its pendingnext_run_at. This makes it safe to call from a Durable Object constructor /onStart, which run again on every wake from hibernation. The next run is only (re)started when you pass an explicitstartAt, changeeveryMs, or revive a cancelled schedule.cancelIntervalmarks the schedulecancelledand deletes anyqueuedruns that were already materialized from it. A run that is alreadyrunningis left alone.setupJobsis safe in a constructor for the same reason: it will not overwrite an alarm that is about to fire. If storage has due work and no alarm is set (for example after a crash), it restores one.- If the Durable Object restarts while a handler is running,
setupJobsqueues that run again with the same job ID. Handlers should usejob.idas an idempotency key because the previous attempt may have completed its external side effects before the restart. - One exception: an interrupted debounced run is dropped instead of requeued when a newer pending run already holds its key. The pending run does the same work with fresher input.
- Completed runs are deleted after their handlers return.
- Failed handlers store their error message and stack. Only the newest
maxFailedJobsPerTyperuns for each type are retained. - Job statuses:
queued,running,failed.
