跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

调度任务

最后更新 查看 MarkdownAgent 设置

Agent 类会安装 Scheduler 功能。其计划方法会调用 scheduler,而 callback 名称是 Agent 上的方法名称。计划存储在 SQLite 中,并从 Lifecycle 的 job queue 运行,因此可以在重启和驱逐后继续存在。有关计划选项、重试、限制和自然语言解析,请参阅 Scheduler 功能。

计划 callback

import { Agent } from "agents";

export class ReminderAgent extends Agent {
	async onStart() {
		// Recurring schedules are idempotent, so this adds one row however often the Agent starts.
		await this.schedule("0 8 * * *", "dailyDigest");
	}

	async remindLater(message) {
		await this.schedule(30, "sendReminder", { message }); // in 30 seconds
		await this.schedule(new Date("2026-12-01T09:00:00Z"), "sendReminder", {
			message,
		});
		await this.scheduleEvery(300, "checkInbox"); // every 5 minutes
	}

	async sendReminder(payload) {
		console.log(payload.message);
	}

	async dailyDigest() {}

	async checkInbox() {}
}
import { Agent } from "agents";

export class ReminderAgent extends Agent<Env> {
	async onStart() {
		// Recurring schedules are idempotent, so this adds one row however often the Agent starts.
		await this.schedule("0 8 * * *", "dailyDigest");
	}

	async remindLater(message: string) {
		await this.schedule(30, "sendReminder", { message }); // in 30 seconds
		await this.schedule(new Date("2026-12-01T09:00:00Z"), "sendReminder", {
			message,
		});
		await this.scheduleEvery(300, "checkInbox"); // every 5 minutes
	}

	async sendReminder(payload: { message: string }) {
		console.log(payload.message);
	}

	async dailyDigest() {}

	async checkInbox() {}
}

Agent 方法

Agent 方法 对应的 Scheduler 方法
schedule(when, callback, payload?, options?) scheduler.set()
scheduleEvery(intervalSeconds, callback, payload?, options?) scheduler.every()
getScheduleById(id) scheduler.get()
listSchedules(criteria?) scheduler.list()
cancelSchedule(id) scheduler.cancel()

when 是以秒为单位的延迟、Date 或 cron 字符串。callback 必须命名 Agent 上的一个方法。getSchedule() 和 getSchedules() 是 getScheduleById() 和 listSchedules() 已弃用的同步版本。

保持 Agent 存活

空闲 Durable Object 在大约 70 到 140 秒内没有请求、消息或 alarm 后会被驱逐。当时正在进行的工作会停止。keepAliveWhile() 会在函数运行时在共享 alarm 上保持 heartbeat,并在函数结束时释放它:

import { Agent } from "agents";

export class ReportAgent extends Agent {
	async buildReport() {
		return this.keepAliveWhile(async () => {
			// Long work that must not be interrupted by idle eviction.
			return "done";
		});
	}
}
import { Agent } from "agents";

export class ReportAgent extends Agent<Env> {
	async buildReport() {
		return this.keepAliveWhile(async () => {
			// Long work that must not be interrupted by idle eviction.
			return "done";
		});
	}
}

对于不适合封装在一个函数中的工作,keepAlive() 会改为返回 disposer。请始终调用 disposer。AIChatAgent 在 streaming 回复期间会保持自身活跃。计划的 callback 和 Workflow 不需要它。

heartbeat 只能防止空闲驱逐。部署或崩溃仍会停止工作,因此对于必须完成的工作,请计划 job 或使用 Workflow。

后续步骤

Scheduler 功能

计划选项、重试、限制以及从自然语言解析计划。

这篇文档对您有帮助吗?