npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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 zod

do-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 (default 50): upper bound of jobs executed per alarm tick.
  • maxFailedJobsPerType (default 100): number of newest failed runs retained for each job type. Set it to 0 to 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. everyMs must 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 same dedupeKey.
  • 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.
  • scheduleInterval is idempotent w.r.t. timing: re-registering an unchanged, still-active schedule preserves its pending next_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 explicit startAt, change everyMs, or revive a cancelled schedule.
  • cancelInterval marks the schedule cancelled and deletes any queued runs that were already materialized from it. A run that is already running is left alone.
  • setupJobs is 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, setupJobs queues that run again with the same job ID. Handlers should use job.id as 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 maxFailedJobsPerType runs for each type are retained.
  • Job statuses: queued, running, failed.