本页还没有译文
本页 24 段还没译成한국어,下面显示的是英文原文。Scheduled Handler
还没翻译译自英文(developers.cloudflare.com)本页 24 段都还没译
Background
When a Worker is invoked via a Cron Trigger, the scheduled() handler handles the invocation.
Testing scheduled() handlers in local development
You can test the behavior of your scheduled() handler in local development by sending an HTTP request to /cdn-cgi/local/scheduled to trigger the handler. Pass ?format=json to return the structured scheduled handler result.
curl "http://localhost:8787/cdn-cgi/local/scheduled?format=json"Syntax
export default {
async scheduled(controller, env, ctx) {
await doSomeTaskOnASchedule();
},
};interface Env {}
export default {
async scheduled(
controller: ScheduledController,
env: Env,
ctx: ExecutionContext,
) {
await doSomeTaskOnASchedule();
},
};from workers import WorkerEntrypoint
class Default(WorkerEntrypoint):
async def scheduled(self, controller, env, ctx):
# controller.cron contains the cron pattern that triggered this event
# controller.scheduledTime contains the scheduled time in ms since epoch
print(f"Cron triggered: {controller.cron}")Properties
controller.cronstring- The value of the Cron Trigger that started the
ScheduledEvent.
- The value of the Cron Trigger that started the
controller.typestring- The type of controller. This will always return
"scheduled".
- The type of controller. This will always return
controller.scheduledTimenumber- The time the
ScheduledEventwas scheduled to be executed in milliseconds since January 1, 1970, UTC. It can be parsed asnew Date(controller.scheduledTime).
- The time the
envobject- An object containing the bindings associated with your Worker using ES modules format, such as KV namespaces and Durable Objects.
ctxobject- An object containing the context associated with your Worker using ES modules format. Currently, this object just contains the
waitUntilfunction.
- An object containing the context associated with your Worker using ES modules format. Currently, this object just contains the
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 * * *"],
},
}[triggers]
crons = [ "*/5 * * * *", "0 0 * * *" ]
export default {
async scheduled(controller, env, ctx) {
switch (controller.cron) {
case "*/5 * * * *":
await fetch("https://example.com/api/sync");
break;
case "0 0 * * *":
await env.MY_KV.put("last-cleanup", new Date().toISOString());
break;
}
},
};export default {
async scheduled(
controller: ScheduledController,
env: Env,
ctx: ExecutionContext,
) {
switch (controller.cron) {
case "*/5 * * * *":
await fetch("https://example.com/api/sync");
break;
case "0 0 * * *":
await env.MY_KV.put("last-cleanup", new Date().toISOString());
break;
}
},
} satisfies ExportedHandler<Env>;from workers import WorkerEntrypoint, fetch
from datetime import datetime, timezone
class Default(WorkerEntrypoint):
async def scheduled(self, controller, env, ctx):
if controller.cron == "*/5 * * * *":
await fetch("https://example.com/api/sync")
elif controller.cron == "0 0 * * *":
await env.MY_KV.put("last-cleanup", datetime.now(timezone.utc).isoformat())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(promise): void - Use this method to register asynchronous tasks (for example, logging, analytics to third-party services, streaming and caching) that should settle before the invocation completes. The firstctx.waitUntilto fail will be observed and recorded as the status in the Cron Trigger Past Events table. Otherwise, it will be reported as a success.
Note
The runtime waits for the promise returned by the scheduled() handler to
resolve (up to the 15-minute duration limit). You do not need to use
waitUntil() for the runtime to wait for a single asynchronous task.
waitUntil() is most useful when you need to run multiple concurrent tasks, or
when you want the outcome of a specific promise to be recorded as the Cron
Trigger invocation status.