Cron 触发器与定时 Workers
使用 Cron Triggers 按计划运行 Cloudflare Workers,在边缘自动执行重复的后台任务。
Cron 触发器与定时 Workers 是 CoddyKit 上的免费 Edge Computing with Cloudflare Workers & Deno 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Edge Computing with Cloudflare Workers & Deno 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Scheduled Workers?
Beyond responding to HTTP requests, Workers can run on a schedule using Cron Triggers.
This is perfect for recurring jobs such as:
- Cleaning up stale data in KV or D1
- Sending daily report emails
- Refreshing cached API responses
- Aggregating analytics
No always-on server required, the Worker simply wakes up, runs, and goes back to sleep.
The scheduled() Handler
A scheduled Worker exports a scheduled() handler instead of (or alongside) fetch().
Cloudflare invokes it automatically at the times you define in cron expressions.
export default {
async scheduled(event, env, ctx) {
console.log('Triggered at: ' + event.scheduledTime);
}
};Configuring Cron in wrangler.toml
Cron schedules live in your wrangler.toml under the [triggers] section.
You can declare multiple cron expressions, each one fires the same scheduled() handler.
[triggers]
crons = ["0 * * * *", "*/15 * * * *"]Cron Expression Syntax
Cloudflare cron expressions have five fields: minute, hour, day-of-month, month, day-of-week.
0 0 * * *means midnight UTC every day*/5 * * * *means every 5 minutes0 9 * * 1means 09:00 UTC every Monday
All times are in UTC.
Distinguishing Multiple Crons
When you register several cron schedules, use event.cron to tell which one fired.
This lets one Worker handle many jobs.
export default {
async scheduled(event, env, ctx) {
if (event.cron === '0 0 * * *') {
await runDailyCleanup(env);
} else if (event.cron === '*/15 * * * *') {
await refreshCache(env);
}
}
};Using waitUntil for Long Tasks
Just like in fetch(), the ctx.waitUntil() method keeps the Worker alive until a promise resolves.
Use it to ensure background async work completes before the invocation ends.
async scheduled(event, env, ctx) {
ctx.waitUntil(syncRemoteData(env));
}Accessing Bindings in scheduled()
The env argument exposes all your bindings: KV, D1, R2, Queues, secrets.
A scheduled cleanup might delete expired KV keys.
async scheduled(event, env, ctx) {
const list = await env.MY_KV.list({ prefix: 'session:' });
for (const key of list.keys) {
await env.MY_KV.delete(key.name);
}
}Testing Crons Locally
Wrangler lets you test scheduled handlers without waiting for the real schedule.
Run wrangler dev and trigger via the test endpoint, or use the CLI flag.
wrangler dev --test-scheduled
# then visit:
# http://localhost:8787/__scheduled?cron=0+*+*+*+*Combining fetch() and scheduled()
A single Worker can export both handlers.
This is handy when the same logic serves HTTP requests and runs on a timer.
export default {
async fetch(request, env) {
return new Response('Hello from fetch');
},
async scheduled(event, env, ctx) {
console.log('Hello from cron');
}
};Monitoring Scheduled Runs
Cron invocations appear in the Cloudflare dashboard and in wrangler tail logs.
Watch for failures, a thrown error means the job did not complete, and there is no automatic retry for cron triggers.
wrangler tail --format prettyLimits & Best Practices
Keep scheduled jobs efficient:
- Stay within CPU time limits, offload heavy work to Queues
- Make jobs idempotent so reruns are safe
- Avoid sub-minute schedules unless necessary
- Log results for observability
Quick Check
Which property tells you which cron schedule triggered the handler?
Recap
You learned how to run Workers on a schedule:
- Export a
scheduled()handler - Define schedules in
[triggers] crons - Use five-field UTC cron expressions
- Route with
event.cronand keep work alive withctx.waitUntil() - Test with
--test-scheduledand monitor withwrangler tail
Cron Triggers turn Workers into reliable edge-native background job runners.
用 AI 导师学习 Edge Computing with Cloudflare Workers & Deno — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 47
常见问题解答
「Cron 触发器与定时 Workers」课时是免费的吗?
是的 — 「Cron 触发器与定时 Workers」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Edge Computing with Cloudflare Workers & Deno 课程的其余内容,请升级到 CoddyKit PRO。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。
「Cron 触发器与定时 Workers」这节课中我会学到什么?
使用 Cron Triggers 按计划运行 Cloudflare Workers,在边缘自动执行重复的后台任务。 你通过在浏览器中直接运行的动手代码来练习 Edge Computing with Cloudflare Workers & Deno,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Edge Computing with Cloudflare Workers & Deno 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Edge Computing with Cloudflare Workers & Deno 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「Cron 触发器与定时 Workers」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Edge Computing with Cloudflare Workers & Deno 课中编写并运行代码吗?
能。每节 Edge Computing with Cloudflare Workers & Deno 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- WebSockets 与实时通信
- 队列与异步任务
- 服务绑定与集成
- Cron 触发器与定时 Workers