Skip to content
Cloudflare Docs

Scheduled Handler

Background

When a Worker is invoked via a Cron Trigger, the scheduled() handler handles the invocation.


Syntax

JavaScript
export default {
async scheduled(controller, env, ctx) {
ctx.waitUntil(doSomeTaskOnASchedule());
},
};

Properties

  • controller.cron string

    • The value of the Cron Trigger that started the ScheduledEvent.
  • controller.type string

    • The type of controller. This will always return "scheduled".
  • controller.scheduledTime number

    • The time the ScheduledEvent was scheduled to be executed in milliseconds since January 1, 1970, UTC. It can be parsed as new Date(controller.scheduledTime).
  • env object

    • An object containing the bindings associated with your Worker using ES modules format, such as KV namespaces and Durable Objects.
  • ctx object

    • An object containing the context associated with your Worker using ES modules format. Currently, this object just contains the waitUntil function.

Handle multiple cron triggers

When you configure multiple Cron Triggers for a single Worker, each trigger invokes the same scheduled() handler. Use controller.cron to distinguish which schedule fired and run different logic for each.

{
"triggers": {
"crons": ["*/5 * * * *", "0 0 * * *"],
},
}
JavaScript
export default {
async scheduled(controller, env, ctx) {
switch (controller.cron) {
case "*/5 * * * *":
ctx.waitUntil(fetch("https://example.com/api/sync"));
break;
case "0 0 * * *":
ctx.waitUntil(env.MY_KV.put("last-cleanup", new Date().toISOString()));
break;
}
},
};

The value of controller.cron is the exact cron expression string from your configuration. It must match character-for-character, including spacing.

Methods

When a Workers script is invoked by a Cron Trigger, the Workers runtime starts a ScheduledEvent which will be handled by the scheduled function in your Workers Module class. The ctx argument represents the context your function runs in, and contains the following methods to control what happens next:

  • ctx.waitUntil(promisePromise) : void - Use this method to notify the runtime to wait for asynchronous tasks (for example, logging, analytics to third-party services, streaming and caching). The first ctx.waitUntil to fail will be observed and recorded as the status in the Cron Trigger Past Events table. Otherwise, it will be reported as a success.