scheduled 事件会根据指定的 Cron 触发器自动分发:
const mf = new Miniflare({
crons: ["15 * * * *", "45 * * * *"],
});因为等待 Cron 触发器可能比较缓慢,你也可以向 /cdn-cgi/mf/scheduled 发送 HTTP 请求来触发 scheduled 事件:
$ curl "http://localhost:8787/cdn-cgi/mf/scheduled"要在分发的事件中模拟 scheduledTime 和 cron 的不同值,请使用 time 和 cron 查询参数:
$ curl "http://localhost:8787/cdn-cgi/mf/scheduled?time=1000"
$ curl "http://localhost:8787/cdn-cgi/mf/scheduled?cron=*+*+*+*+*"在使用 API 时,可以使用 getWorker 函数向你的 Worker 分发 scheduled 事件。这可以用于测试响应。它接受可选的 scheduledTime 和 cron 参数,默认值分别为当前时间和空字符串。它将返回一个 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 }