Cloudflare Cron Triggers: run a Worker on a schedule
By Flavio
Tagged: Cloudflare
How to run a Cloudflare Worker on a schedule with Cron Triggers. Nightly jobs, periodic checks, and cleanups, with no server to keep running.
Not everything happens because someone visits a URL. Some things should just run on their own: a nightly report, a cleanup every hour, a check every five minutes.
For that, Cloudflare has Cron Triggers. You give a Worker a schedule, and Cloudflare runs it for you. No server sitting idle, no cron daemon to babysit.
Add a schedule
Schedules go in wrangler.jsonc, under triggers:
{
"triggers": {
"crons": ["0 2 * * *"]
}
}
That string is a cron expression. 0 2 * * * means “every day at 2:00.” You can have more than one schedule in the array.
A few common ones:
*/5 * * * *— every 5 minutes0 * * * *— every hour, on the hour0 2 * * *— every day at 2:000 0 * * MON— every Monday at midnight
On Cloudflare, 1 in the weekday field is Sunday. 7 is Saturday. That’s not the usual Unix numbering, so write MON when you want Monday.
If cron syntax makes your eyes glaze over, a tool like crontab.guru spells it out in plain English. I also built a free cron builder that does the same and previews the next run times.
Handle the schedule
A normal Worker has a fetch handler. A scheduled Worker has a scheduled handler instead (or as well):
export default {
async scheduled(event, env, ctx) {
console.log('Running the nightly job')
// do the work here
},
}
Cloudflare calls scheduled on your schedule. You get env with all your bindings, so you can read your database, write to storage, send email, whatever the job needs.
A real example
Here’s a nightly cleanup that deletes old rows from a D1 database:
export default {
async scheduled(event, env, ctx) {
const thirtyDaysAgo = Date.now() - 30 * 24 * 60 * 60 * 1000
await env.DB.prepare(
'delete from logs where created_at < ?'
).bind(thirtyDaysAgo).run()
},
}
Set it to 0 2 * * * and your logs table cleans itself up every night while you sleep.
More than one schedule
Every expression in crons calls the same scheduled handler. The first argument has an event.cron string, and that is how you tell the runs apart.
{
"triggers": {
"crons": ["0 * * * *", "0 8 * * *"]
}
}
export default {
async scheduled(event, env, ctx) {
switch (event.cron) {
case '0 * * * *':
await pruneLogs(env)
break
case '0 8 * * *':
await sendDailyDigest(env)
break
}
},
}
The value is the exact expression from wrangler.jsonc. Spaces included. If the config says 0 8 * * * and the case says 0 8 * * * with a trailing space, that branch never runs.
Be careful with time zones
Here’s the one thing that trips people up. Cron schedules run in UTC, not your local time.
So 0 9 * * * is 9:00 UTC, which might be the middle of the night where you are. If you want a job at 9:00 your time, convert to UTC first.
Long jobs and waitUntil
The runtime already waits for scheduled to finish, up to 15 minutes. You don’t need ctx.waitUntil for a single await.
Use it when you kick off extra work that should still finish, or when you want that promise to decide the success or failure in Cron Events:
async scheduled(event, env, ctx) {
ctx.waitUntil(generateDailyReport(env))
}
The first waitUntil promise that rejects is the status Cloudflare stores for that run.
Testing it locally
You don’t want to wait until 2 AM to know if your job works. In dev, you can trigger it with Wrangler:
npx wrangler dev
Then in another terminal, hit the test endpoint Wrangler exposes:
curl "http://localhost:8787/cdn-cgi/local/scheduled"
That runs your scheduled handler right away. Older tutorials use /cdn-cgi/handler/scheduled, which still redirects. Add ?cron= if you want to simulate a specific schedule.
When a run fails
If scheduled throws, that invocation is a failure. A rejected waitUntil promise is a failure too. Cron Triggers don’t retry a failed step the way Queues or Workflows do. The next attempt is the next scheduled time.
To see past runs, open the Worker in the dashboard, go to Settings, then Trigger Events, then View events. That list is Cron Events. It keeps the last 100 invocations.
console.log output lives in Workers Logs, with a longer retention and a search box. For a live stream from the deployed Worker:
npx wrangler tail
A brand new Worker, or a rename, can take up to 30 minutes before anything shows up in Cron Events.
After you deploy
npx wrangler deploy publishes the Worker and the schedules together. Adding, changing, or deleting a cron can take several minutes, up to 15, to reach the whole network.
Wrangler replaces the deployed schedule list with whatever you put in triggers.crons.
To remove every schedule, deploy an empty array:
{
"triggers": {
"crons": []
}
}
If you delete the triggers key, or leave crons out, the schedules already on the Worker stay there. Commenting crons out does the same. The empty array is what clears them.
Limits that matter
Per account, the Free plan allows 5 Cron Triggers. The Paid plan allows 250. Two expressions on one Worker count as two triggers.
A scheduled run can stay alive for 15 minutes of wall time. After that, Cloudflare stops it.
CPU time is separate. Waiting on fetch(), D1, or KV does not count. On the Free plan you get 10 ms of CPU per run. On Paid, a job that fires more often than once an hour gets 30 seconds. A job that fires once an hour or less gets 15 minutes.
If the work needs more than that, move it off the cron handler.
When cron is the wrong tool
A Cron Trigger is the right tool when the work is short and periodic, like a nightly cleanup or a daily digest.
Use Queues when a run should be retried, batched, or split across consumers. A common pattern is the cron handler only send()s a message, and the queue handler does the work.
Use Workflows when the job has several steps that depend on each other, or needs to pause and come back. Each step is saved. If step 3 fails, only step 3 retries. You can attach cron expressions on the Workflow binding, so you don’t need a separate scheduled handler just to start it. The setup is in the Trigger Workflows docs.
What I use it for
Cron Triggers are my go-to for the quiet background chores: rolling up analytics overnight, pruning old data, checking if a site is up, sending a daily digest.
It’s the simplest way to run code on a schedule without owning a server. The full reference is in the Cron Triggers docs.
Want me to talk about your product? You can sponsor this site.
Related posts about cloudflare: