Background Work Without a Server
Cron: Work That Runs on the Clock
A Schedule and a Function
This site has two schedules. They send reminders, publish scheduled posts and clean up old data. This piece goes inside wrangler.jsonc:
"triggers": { "crons": ["*/15 * * * *", "0 8 * * *"] }
Every 15 minutes, and once a day at 08:00. That's UTC, always. 08:00 UTC is 1am in Denver in winter and 2am in summer. If your users care about local time, say so in the spec.
The Trap: It Runs Twice
Look at those two schedules again. At 08:00 both fire. If your code doesn't check which one woke it up, the same work runs twice at the same moment. That's an easy gap to miss. The fix is to check the trigger, and for anything that must happen once, claim it in the database first:
async scheduled(event, env, ctx) {
// Only the daily trigger sends the report
if (event.cron !== "0 8 * * *") return;
// Claim the day. A second run inserts nothing and stops here.
const day = new Date(event.scheduledTime).toISOString().slice(0, 10);
const claim = await env.DB
.prepare("INSERT OR IGNORE INTO report_runs (run_day) VALUES (?)")
.bind(day)
.run();
if (claim.meta.changes === 0) return;
await sendReport(env, day);
},
run_day is the table's primary key, so the second insert changes zero rows and quits.
That's a choice, though: if sendReport fails after the claim, nothing retries today. For a report that beats sending it twice. If missing one is worse, have the cron put a job in a queue and let the queue retry. You make that call. AI won't know which one hurts you.
Other Walls
- A cron run gets up to 15 minutes of wall time.
- A new or changed schedule can take up to 15 minutes to take effect.
- Test it without waiting. With
npx wrangler devrunning:
curl "http://localhost:8787/cdn-cgi/local/scheduled?cron=0+8+*+*+*"
After the first deploy of a new cron, check Cron Events in the dashboard and see that it fired. A brand-new cron can deploy cleanly and still not fire until you run npx wrangler triggers deploy. A job that never starts doesn't log an error.
Your crons are every 15 minutes and daily at 08:00 UTC. What happens at 08:00?