Prompt
How do I handle cron jobs in Cloudflare Workers?
Latest observation
Cloudflare Workers don’t run on a traditional always-on server, so you handle cron jobs with Cloudflare Cron Triggers (also called schedules).
The basic idea
Instead of a cron daemon running on your machine, Cloudflare invokes your Worker on a schedule you define, like:
- every minute
- every hour
- daily at a certain time
- custom cron expressions
How to set it up
1) Define a scheduled handler in your Worker
In your Worker code, add a scheduled() function:
export default {
async scheduled(event, env, ctx) {
console.log("Cron triggered at:", new Date().toISOString());
await doSomeTask();
}
};
async function doSomeTask() {
// your job logic here
}
2) Configure the cron schedule
In wrangler.toml:
name = "my-worker"
main = "src/index.js"
compatibility_date = "2026-01-01"
[triggers]
crons = ["0 * * * *"] # every hour
You can add multiple cron expressions:
[triggers]
crons = ["*/5 * * * *", "0 0 * * *"]
3) Deploy
wrangler deploy
Cloudflare will invoke your Worker on that schedule.
Important considerations
Workers are short-lived
A scheduled Worker has execution limits, so cron jobs should be:
- relatively quick
- idempotent
- able to resume safely if retried
If you have long-running work, split it into smaller units or hand it off to another system.
Use Durable Objects, Queues, or external services for heavier work
For more complex workflows:
- Durable Objects: coordination, state, locking
- Queues: fan-out/background processing
- External APIs / databases: store job state and progress
Avoid duplicate work
Cron triggers can occasionally be delivered more than once, so design jobs to be safe if rerun.
Common patterns:
- store the last successful run timestamp
- use a lock
- make processing idempotent
Testing locally
You can simulate scheduled events with Wrangler, though the exact support depends on your Wrangler version/workflow. In practice, many people test by:
- calling the logic from a normal HTTP handler
- extracting the job logic into a shared function
- running it in development with a mock scheduled event
If you want a schedule in code, but no cron syntax
If your schedule is more complex than cron expressions, you can:
- trigger the Worker every minute
- decide in code whether to run the job based on current time / state
Summary
Use Cloudflare Cron Triggers:
- add a
scheduled()handler - configure
[triggers].cronsinwrangler.toml - keep jobs short and idempotent
- use Durable Objects/Queues for heavier workflows
If you want, I can also show:
- a TypeScript example,
- how to test scheduled events locally, or
- how to use Durable Objects with cron jobs.