跳转到内容
搜索文档

定时触发事件 (Scheduled Events)

最后更新 查看 MarkdownAgent 设置

Cron 触发器 (Cron Triggers)

scheduled 事件会根据指定的 Cron 触发器自动分发:

const mf = new Miniflare({
	crons: ["15 * * * *", "45 * * * *"],
});

HTTP 触发器 (HTTP Triggers)

因为等待 Cron 触发器可能比较缓慢,你也可以向 /cdn-cgi/mf/scheduled 发送 HTTP 请求来触发 scheduled 事件:

$ curl "http://localhost:8787/cdn-cgi/mf/scheduled"

要在分发的事件中模拟 scheduledTimecron 的不同值,请使用 timecron 查询参数:

$ curl "http://localhost:8787/cdn-cgi/mf/scheduled?time=1000"
$ curl "http://localhost:8787/cdn-cgi/mf/scheduled?cron=*+*+*+*+*"

分发事件 (Dispatching Events)

在使用 API 时,可以使用 getWorker 函数向你的 Worker 分发 scheduled 事件。这可以用于测试响应。它接受可选的 scheduledTimecron 参数,默认值分别为当前时间和空字符串。它将返回一个 Promise,解析为包含所有被等待 Promise 所返回数据的数组:

import { Miniflare } from "miniflare";

const mf = new Miniflare({
	modules: true,
	script: `
  export default {
    async scheduled(controller, env, ctx) {
      const lastScheduledController = controller;
      if (controller.cron === "* * * * *") controller.noRetry();
    }
  }
  `,
});

const worker = await mf.getWorker();

let scheduledResult = await worker.scheduled({
	cron: "* * * * *",
});
console.log(scheduledResult); // { outcome: 'ok', noRetry: true }

scheduledResult = await worker.scheduled({
	scheduledTime: new Date(1000),
	cron: "30 * * * *",
});

console.log(scheduledResult); // { outcome: 'ok', noRetry: false }

这篇文档对您有帮助吗?