Gatilhos Cron e Workers agendados
Execute Cloudflare Workers conforme uma agenda com Cron Triggers para automatizar tarefas recorrentes em segundo plano na borda.
Gatilhos Cron e Workers agendados é uma aula grátis de Edge Computing with Cloudflare Workers & Deno no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Edge Computing with Cloudflare Workers & Deno, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Edge Computing with Cloudflare Workers & Deno inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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.
Aprenda Edge Computing with Cloudflare Workers & Deno com um tutor de IA — grátis
Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.
- Cursos
- 12
- Aulas
- 47
Perguntas Frequentes
A aula “Gatilhos Cron e Workers agendados” é grátis?
Sim — o texto completo de “Gatilhos Cron e Workers agendados” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Edge Computing with Cloudflare Workers & Deno, atualize para CoddyKit PRO. O curso de Edge Computing with Cloudflare Workers & Deno inclui 4 aulas no total.
O que vou aprender em “Gatilhos Cron e Workers agendados”?
Execute Cloudflare Workers conforme uma agenda com Cron Triggers para automatizar tarefas recorrentes em segundo plano na borda. Você pratica Edge Computing with Cloudflare Workers & Deno com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Edge Computing with Cloudflare Workers & Deno?
Nenhuma experiência prévia é necessária. Edge Computing with Cloudflare Workers & Deno no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Gatilhos Cron e Workers agendados”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Edge Computing with Cloudflare Workers & Deno?
Sim. Cada aula de Edge Computing with Cloudflare Workers & Deno inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- WebSockets e tempo real
- Filas e tarefas assíncronas
- Vinculações de serviços e integrações
- Gatilhos Cron e Workers agendados