Project

Examples

Runnable scripts from the repository. Clone it, install, and run any of them with Bun.

On this page
git clone https://github.com/chaqchase/cronbake.git
cd cronbake
bun install
bun run examples/basic.ts

The scripts in the repository import from the local source. They’re shown here with the package import you’d use in your own code.

Basic

Two in-memory jobs, with a clean exit on Ctrl+C.

examples/basic.ts
import Baker from "cronbake";

async function main() {
  const baker = Baker.create({
    autoStart: true,
  });

  baker.add({
    name: "log-every-minute",
    cron: "@every_minute",
    callback: () => {
      console.log(`[${new Date().toISOString()}] Hello from Cronbake!`);
    },
  });

  baker.add({
    name: "at-noon",
    cron: "0 0 12 * * *",
    callback: () => {
      console.log("It's noon somewhere! Time to stretch.");
    },
  });

  const shutdown = () => {
    console.log("Stopping all jobs...");
    baker.stopAll();
    process.exit(0);
  };

  process.once("SIGINT", shutdown);
  process.once("SIGTERM", shutdown);
}

main().catch((error) => {
  console.error("Example failed:", error);
  process.exit(1);
});

Persistence

A file-backed baker with one job that’s saved and one that isn’t. It waits for ready() before adding anything, and saves on the way out.

examples/persistence.ts
import Baker, { FilePersistenceProvider } from "cronbake";

async function main() {
  const baker = Baker.create({
    autoStart: true,
    persistence: {
      enabled: true,
      strategy: "file",
      provider: new FilePersistenceProvider("./.cronbake-state.json"),
      autoRestore: true,
    },
  });

  await baker.ready();

  baker.add({
    name: "daily-report",
    cron: "@daily",
    persist: true,
    callback: () => {
      console.log(`[${new Date().toISOString()}] Generating daily summary...`);
    },
  });

  baker.add({
    name: "ephemeral-debug",
    cron: "@every_10_seconds",
    persist: false,
    callback: () => {
      console.log("Debug job ran – this will not be restored after restart.");
    },
  });

  const shutdown = async () => {
    console.log("Stopping all jobs and saving state...");
    baker.stopAll();
    await baker.saveState();
    process.exit(0);
  };

  process.once("SIGINT", shutdown);
  process.once("SIGTERM", shutdown);
}

main().catch((error) => {
  console.error("Persistence example failed:", error);
  process.exit(1);
});

Logging

examples/logging.ts builds a coloured logger, uses it for the baker, overrides it for one job, and includes a job that fails at random so you can see the error output.

More in-depth patterns are in the guides: shutting down cleanly, taking a lock, retrying failures and reporting job status.

esc

Try overlap, restore or timezone.