跳转到内容
搜索文档

Scheduled 处理器

最后更新 查看 MarkdownAgent 设置

背景

当 Worker 通过 Cron Trigger 调用时,scheduled() 处理器负责处理该调用。


语法

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}")

属性

  • controller.cron string

  • controller.type string

    • 控制器的类型。该值始终返回 "scheduled"
  • controller.scheduledTime number

    • ScheduledEvent 计划执行的时间,以 UTC 时间 1970 年 1 月 1 日以来的毫秒数表示。可使用 new Date(controller.scheduledTime) 解析。
  • env object

    • 包含与 Worker 关联的绑定(使用 ES modules 格式),例如 KV 命名空间和 Durable Objects。
  • ctx object

    • 包含与 Worker 关联的上下文(使用 ES modules 格式)。目前,该对象仅包含 waitUntil 函数。

处理多个 cron trigger

当你为单个 Worker 配置多个 Cron Trigger 时,每个 trigger 都会调用同一个 scheduled() 处理器。使用 controller.cron 区分触发了哪个计划,并为每个计划执行不同逻辑。

{
	"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())

controller.cron 的值来自配置中的 cron 表达式字符串。必须逐字符完全匹配,包括空格。

方法

当 Workers 脚本由 Cron Trigger 调用时,Workers 运行时会启动一个 ScheduledEvent,由 Workers Module 类中的 scheduled 函数处理。ctx 参数表示函数运行的上下文,并包含以下方法以控制后续行为:

  • ctx.waitUntil(promise) : void - 使用此方法注册异步任务(例如日志记录、向第三方服务发送分析数据、流式传输和缓存),这些任务应在调用完成前结束。第一个失败的 ctx.waitUntil 会被记录,并作为 Cron Trigger「过去事件」表中的状态。否则将报告为成功。

这篇文档对您有帮助吗?