Cloud and deployment · Intermediate · 17 min
Run scheduled jobs with Cloudflare Workers cron triggers
By Padding · Updated 18 Nov 2026
Node.js 26 · Wrangler 4.168.0 · Vitest 4.1.12
You will have a Worker that runs two jobs on cron triggers, a health check every ten minutes and a daily digest at 08:00 Lagos time, fired by hand in local development, covered by Vitest tests and ready to deploy.
On this page
A Worker usually wakes up when a request arrives. With a cron trigger, it also wakes up on a schedule you set, with no request and no server of your own. That makes it a good home for small recurring jobs: checking that a site is up, sending a morning summary, clearing out stale records, calling an API that has to be polled.
In this tutorial you build one Worker, uptime-digest, with two jobs. Every ten minutes it checks a health URL and sends an alert if the site is down. Every morning at 08:00 Lagos time it posts a short digest to a webhook. You add a scheduled() handler and the schedules, fire both jobs by hand in local development, write tests with Vitest, and then deploy and read the past runs.
Locally, nothing calls the internet. A small Node.js script stands in for your site and your webhook, so you can make the site go "down" on demand and see the alert arrive. If you are working on prepaid data, that also means the only download is the npm install in the first step.
Step 1 · Create the project and install Wrangler
Make a throwaway folder for the project and install Wrangler as a development dependency. The exact version keeps the commands below matching what you see:
mkdir -p ~/cron-demo/src ~/cron-demo/test
cd ~/cron-demo
npm init -y > /dev/null
npm pkg set type=module
npm install --save-dev --save-exact wrangler@4.168.0type=module tells Node.js to treat the project's .js and config files as ES modules, which the test tooling in a later step expects.
Check it worked
npx wrangler --versionThe output includes 4.168.0.
Step 2 · Write the scheduled handler
A Worker's default export can have a fetch() handler for requests and a scheduled() handler for cron triggers. scheduled() receives three arguments:
controller, aScheduledController.controller.cronis the schedule that fired, as written in your config, andcontroller.scheduledTimeis when it was due, in milliseconds since 1970 in UTC. Older examples call this argumentevent; it is the same object.env, your variables, secrets and bindings.ctx, whosewaitUntil()keeps the invocation open until a promise settles, after the handler itself has returned.
One Worker can have several schedules, and they all call the same scheduled() function. Switch on controller.cron to decide which job to run. Create src/index.ts:
cat > src/index.ts <<'TS'
interface Env {
HEALTH_URL: string;
REPORT_URL: string;
}
const EVERY_TEN_MINUTES = "*/10 * * * *";
const DAILY_0700_UTC = "0 7 * * *";
async function checkHealth(env: Env): Promise<{ ok: boolean; status: number }> {
try {
const res = await fetch(env.HEALTH_URL, { signal: AbortSignal.timeout(5000) });
return { ok: res.ok, status: res.status };
} catch {
return { ok: false, status: 0 };
}
}
async function report(env: Env, body: Record<string, unknown>): Promise<void> {
const res = await fetch(env.REPORT_URL, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) throw new Error(`report failed with status ${res.status}`);
}
export default {
async fetch(): Promise<Response> {
return new Response("uptime-digest runs on a schedule.\n", { status: 404 });
},
async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {
const at = new Date(controller.scheduledTime).toISOString();
switch (controller.cron) {
case EVERY_TEN_MINUTES: {
const health = await checkHealth(env);
console.log(`health ${health.ok ? "ok" : "down"} status=${health.status} at=${at}`);
if (!health.ok) {
ctx.waitUntil(report(env, { kind: "alert", status: health.status, at }));
}
break;
}
case DAILY_0700_UTC:
console.log(`daily digest at=${at}`);
ctx.waitUntil(report(env, { kind: "digest", at }));
break;
default:
console.warn(`no job for cron "${controller.cron}"`);
}
},
} satisfies ExportedHandler<Env>;
TSA few choices are worth knowing about:
- The cron strings in the code must match the config exactly, character for character. Keeping them in named constants makes a mismatch easy to spot.
- The health check has a five-second timeout, so a hanging site cannot hold the job open. A failed connection counts as down, with status
0. report()throws when the webhook answers with an error. Because the report runs insidectx.waitUntil(), that failure is what Cloudflare records as the run's status. A run with no failedwaitUntil()promise is recorded as a success.- The
fetch()handler answers every request with a 404 and a short note, so anyone who finds the Worker's URL learns nothing and triggers nothing.
The ScheduledController, ExecutionContext and ExportedHandler types come from the Workers runtime. Wrangler compiles the file without them, but for editor checking, run npx wrangler types once your config is in place; it writes a worker-configuration.d.ts file that describes them.
Check it worked
grep -c "case " src/index.tsThe output is 2: one case per schedule.
Step 3 · Add the cron triggers
Schedules live in triggers.crons in the Wrangler config, using the familiar five fields: minute, hour, day of month, month and day of week. Cron triggers always run in UTC. There is no time zone setting, so convert local times yourself:
- Lagos, Kinshasa and the rest of West Africa Time are UTC+1 all year, so 08:00 in Lagos is
0 7 * * *. - Johannesburg (SAST) is UTC+2, so 08:00 there is
0 6 * * *. - Nairobi (EAT) is UTC+3, so 08:00 there is
0 5 * * *.
None of those zones changes its clocks, so the conversion holds all year. For a city that does observe daylight saving, a fixed UTC schedule moves by an hour against local time twice a year.
Create wrangler.jsonc:
cat > wrangler.jsonc <<'JSONC'
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "uptime-digest",
"main": "src/index.ts",
"compatibility_date": "2026-11-18",
"observability": { "enabled": true },
"vars": {
// Replace this with the health URL of a site you run.
"HEALTH_URL": "https://example.com/"
},
"triggers": {
// UTC. 07:00 UTC is 08:00 in Lagos.
"crons": ["*/10 * * * *", "0 7 * * *"]
}
}
JSONCHEALTH_URL is not secret, so it sits in vars. The webhook address, REPORT_URL, often carries a token in the URL, so it is a secret: you set it with a prompt when you deploy, and locally in a private file in the next step. It never goes in wrangler.jsonc.
Two schedules use two of your account's cron triggers. On the Workers Free plan an account has 5 in total, across all its Workers; on Workers Paid it has 1,000. If you need more jobs than that, run one frequent schedule and decide inside the handler which jobs are due.
Check it worked
Ask Wrangler to build the Worker and read the config without uploading anything:
npx wrangler deploy --dry-run > dry-run.log 2>&1
cat dry-run.logThe output lists HEALTH_URL among the bindings and ends with --dry-run: exiting now. A typo in the JSON, or a main file that does not exist, stops it with an error instead. Remove the log with rm dry-run.log when you have read it.
rm dry-run.logStep 4 · Run both jobs on your machine
Local development does not fire cron triggers on their own, so you fire them by hand. First you need something for the jobs to talk to. Create mock-upstream.mjs, a tiny server that plays your site and your webhook. GET /health answers 200 or 503, GET /toggle switches between them, and POST /report prints whatever it receives:
cat > mock-upstream.mjs <<'JS'
import { createServer } from "node:http";
let healthy = true;
createServer((req, res) => {
if (req.url === "/health") {
res.writeHead(healthy ? 200 : 503).end(healthy ? "up\n" : "down\n");
} else if (req.url === "/toggle") {
healthy = !healthy;
console.log(`health is now ${healthy ? "up" : "down"}`);
res.end(`healthy=${healthy}\n`);
} else if (req.method === "POST" && req.url === "/report") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
console.log(`report ${body}`);
res.writeHead(204).end();
});
} else {
res.writeHead(404).end();
}
}).listen(9000, "127.0.0.1", () => console.log("mock upstream on http://127.0.0.1:9000"));
JSNext, point the Worker at it for local runs. Wrangler reads a .dev.vars file during local development, and its values take the place of vars and secrets. Create it private from the start, and keep it out of Git, because in a real project it holds secrets:
(umask 077 && cat > .dev.vars <<'EOF'
HEALTH_URL=http://127.0.0.1:9000/health
REPORT_URL=http://127.0.0.1:9000/report
EOF
)
printf 'node_modules/\n.wrangler/\n.dev.vars\n' > .gitignoreIn your second terminal, from ~/cron-demo, start the stand-in and leave it running:
node mock-upstream.mjsIn your first terminal, start the Worker. --test-scheduled adds a /__scheduled route that runs scheduled() with the cron you pass:
npx wrangler dev --test-scheduledWrangler prints something like Ready on http://localhost:8787. Open a third terminal, or use the second one in a new tab, and fire the ten-minute job. In a URL, + stands for a space, so */10+*+*+*+* is */10 * * * *:
curl -s "http://127.0.0.1:8787/__scheduled?cron=*/10+*+*+*+*"Then fire the daily digest:
curl -s "http://127.0.0.1:8787/__scheduled?cron=0+7+*+*+*"Wrangler 4.168 also accepts the same query on /cdn-cgi/local/scheduled, with or without --test-scheduled, and adds an optional time parameter in milliseconds to set controller.scheduledTime:
curl -s "http://127.0.0.1:8787/cdn-cgi/local/scheduled?cron=0+7+*+*+*&time=1795590000000"
echo1795590000000 is 07:00 UTC on 25 November 2026, so the digest from this call carries that date.
Check it worked
The first two calls print Ran scheduled event. In the Wrangler terminal you see health ok status=200 at=... and two daily digest at=... lines. In the mock terminal you see two report {"kind":"digest",...} lines, the second with "at":"2026-11-25T07:00:00.000Z", and no alert, because the site is up.
Step 5 · Send an alert when the site is down
Now make the stand-in site fail and fire the health check again:
curl -s http://127.0.0.1:9000/toggle
curl -s "http://127.0.0.1:8787/__scheduled?cron=*/10+*+*+*+*"This time the job takes the other branch. It logs the failure, then hands the alert to ctx.waitUntil(). The handler returns straight away, and the Workers runtime keeps the invocation alive until the alert's fetch has finished. Without waitUntil() or an await, the runtime could end the invocation while the request is still in flight, and the alert would be lost.
Fire a schedule your code does not know, to see the fallback:
curl -s "http://127.0.0.1:8787/__scheduled?cron=0+0+1+*+*"Then put the site back up:
curl -s http://127.0.0.1:9000/toggleCheck it worked
The mock terminal prints health is now down, then report {"kind":"alert","status":503,"at":"..."}, and finally health is now up. The Wrangler terminal shows health down status=503 and a warning, no job for cron "0 0 1 * *". In production that warning is your sign that the config and the code have drifted apart.
Stop both servers with Ctrl+C in their terminals.
Step 6 · Test the jobs with Vitest
Firing jobs by hand proves they work today. Tests keep them working. Cloudflare's Vitest plugin, @cloudflare/vitest-plugin, runs your tests inside the same workerd runtime that Wrangler uses, and gives you helpers to build the controller and ctx arguments. It replaces the older @cloudflare/vitest-pool-workers package, which is deprecated, and it needs Vitest 4.1 or later.
npm install --save-dev --save-exact vitest@4.1.12 @cloudflare/vitest-plugin@1.9.2
npm pkg set scripts.test="vitest run"Create vitest.config.ts, which points the plugin at your Wrangler config:
cat > vitest.config.ts <<'TS'
import { cloudflareTest } from "@cloudflare/vitest-plugin";
import { defineConfig } from "vitest/config";
export default defineConfig({
plugins: [cloudflareTest({ wrangler: { configPath: "./wrangler.jsonc" } })],
});
TSThen write the tests. Each one replaces fetch with a fake, so no request leaves your machine, calls scheduled() directly, and waits for every waitUntil() promise with waitOnExecutionContext() before it checks what was sent:
cat > test/scheduled.test.ts <<'TS'
import {
createExecutionContext,
createScheduledController,
waitOnExecutionContext,
} from "cloudflare:test";
import { afterEach, describe, expect, it, vi } from "vitest";
import worker from "../src/index";
const env = {
HEALTH_URL: "https://health.example.test/",
REPORT_URL: "https://hooks.example.test/report",
};
function fakeFetch(healthStatus: number) {
return vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
const url = input instanceof Request ? input.url : String(input);
if (url === env.HEALTH_URL) return new Response("", { status: healthStatus });
return new Response(null, { status: 204 });
});
}
async function run(cron: string) {
const controller = createScheduledController({
cron,
scheduledTime: Date.UTC(2026, 10, 18, 7, 0),
});
const ctx = createExecutionContext();
await worker.scheduled(controller, env, ctx);
await waitOnExecutionContext(ctx);
}
afterEach(() => {
vi.restoreAllMocks();
});
describe("scheduled jobs", () => {
it("posts the daily digest at 07:00 UTC", async () => {
const fetchMock = fakeFetch(200);
await run("0 7 * * *");
expect(fetchMock).toHaveBeenCalledTimes(1);
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe(env.REPORT_URL);
expect(JSON.parse(String(init?.body))).toEqual({
kind: "digest",
at: "2026-11-18T07:00:00.000Z",
});
});
it("only checks health when the site is up", async () => {
const fetchMock = fakeFetch(200);
await run("*/10 * * * *");
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0]).toBe(env.HEALTH_URL);
});
it("sends an alert when the site is down", async () => {
const fetchMock = fakeFetch(503);
await run("*/10 * * * *");
expect(fetchMock).toHaveBeenCalledTimes(2);
const [url, init] = fetchMock.mock.calls[1];
expect(url).toBe(env.REPORT_URL);
expect(JSON.parse(String(init?.body))).toMatchObject({ kind: "alert", status: 503 });
});
it("warns about a schedule it does not know", async () => {
const fetchMock = fakeFetch(200);
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
await run("0 0 1 * *");
expect(fetchMock).not.toHaveBeenCalled();
expect(warn).toHaveBeenCalledWith('no job for cron "0 0 1 * *"');
});
});
TS
npm testThe tests build their own env object, so they never depend on .dev.vars or your real webhook.
Check it worked
Vitest reports one test file and 4 passed. To see a failure, change "0 7 * * *" in the first test to "0 8 * * *" and run npm test again: the digest test fails because no report was sent. Change it back afterwards.
Step 7 · Deploy and read past runs
This step needs your Cloudflare account. Before you deploy, replace HEALTH_URL in wrangler.jsonc with a page on a site you run, and have a webhook URL ready (for example, an incoming webhook from your team chat tool).
Sign in, store the webhook address as a secret, and deploy. wrangler secret put prompts for the value, so it never lands in your shell history:
npx wrangler login
npx wrangler secret put REPORT_URL
npx wrangler deployThe deploy output lists the Worker's URL and both schedules. New or changed schedules can take up to 15 minutes to reach every Cloudflare location, and runs due in that window can be missed, so do not judge the first quarter of an hour.
To watch runs as they happen, stream the Worker's logs:
npx wrangler tailWithin ten minutes a health check appears, with the same health ok status=... line you saw locally.
For history, open the Cloudflare dashboard, go to Workers & Pages, select uptime-digest, then Settings. Under Trigger Events, select View events. The list keeps the 100 most recent cron invocations, each with its schedule, time and outcome. A run whose report failed shows as an error there, because of the waitUntil() rule from the handler step. With observability turned on in the config, Workers Logs keeps the console.log lines for longer.
Mind the limits for each run. On Workers Free, a cron invocation may use 10 ms of CPU time; waiting for fetch does not count, so a job like this one fits easily. Any cron invocation may run for at most 15 minutes of wall time.
Check it worked
Your chosen site's health check shows in wrangler tail within ten minutes, and after the next 07:00 UTC the dashboard's event list shows a 0 7 * * * run and your webhook has received a digest.
Step 8 · Change or remove schedules
To change a schedule, edit triggers.crons and deploy again. The deployed list is replaced by the one in your config.
To stop all scheduled runs but keep the Worker, set the list to empty and deploy:
"triggers": {
"crons": []
}An empty list removes every trigger. Deleting the triggers block, or the crons key, does not: Cloudflare keeps the schedules that are already deployed, so a Worker you thought you had switched off keeps running.
When you are finished with the demo, delete the deployed Worker, which also removes its schedules, and then the project folder:
npx wrangler deletecd ~
rm -rf ~/cron-demoCheck it worked
The uptime-digest Worker no longer appears under Workers & Pages in the dashboard, and ls ~/cron-demo reports that the folder does not exist.
Next steps
- Compare the same five-field syntax on your own server, where the time zone is yours to set: schedule jobs with cron.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials