Cloudflare Agents 从入门到精通
附录

§12 调度与队列:让 Agent 真正自动跑起来

12.1 四种调度模式

底层用 Durable Object alarm,任务持久化进 SQLite,重启不丢。

模式 语法 用例
延迟 schedule(60, ...) 60 秒后
定时 schedule(new Date(...), ...) 指定时刻
Cron schedule("0 8 * * *", ...) 每天 8 点
间隔 scheduleEvery(30, ...) 每 30 秒

12.2 一个提醒 Agent

export class ReminderAgent extends Agent {
  async onRequest(request: Request) {
    // 30 秒后发提醒
    await this.schedule(30, "sendReminder", { message: "Check email" });
    // 每天 8 点发日报
    await this.schedule("0 8 * * *", "dailyDigest", { userId: "u1" });
    return new Response("Scheduled!");
  }

  async sendReminder(payload: any) { console.log(payload.message); }
  async dailyDigest(payload: any) { /* 生成并发送 */ }
}

12.3 管理调度

const all = await this.listSchedules();              // 全部
const cron = await this.listSchedules({ type: "cron" }); // 只 cron
await this.cancelSchedule(scheduleId);               // 取消

12.4 队列:瞬时高并发

调度是"未来某刻跑一次"。队列是"现在塞进去,按顺序跑"。

await this.queue("processTask", { taskId: "123" });
// 回调:async processTask(payload) { ... }
维度 schedule queue 标叔的结论
语义 定时/延迟 异步入队 看要不要定时
重叠保护 间隔内建 顺序消费 队列防挤兑
典型 日报、提醒 批量任务 各用各的
核心建议
cron 放 onStart() 里设,利用幂等避免重启重复创建。调度是 Agent 自动化的起点。

调度讲完。下一章讲怎么把一个大 Agent 拆成一群小 Agent。