← Cloudflare Workers / workers / examples
Несколько Cron Triggers
Если вы хотите быстро начать, нажмите на кнопку ниже.
Это создаёт репозиторий в вашем аккаунте GitHub и разворачивает приложение в Cloudflare Workers.
export default {
async scheduled(event, env, ctx) {
// Write code for updating your API
switch (event.cron) {
case "*/3 * * * *":
// Every three minutes
await updateAPI();
break;
case "*/10 * * * *":
// Every ten minutes
await updateAPI2();
break;
case "*/45 * * * *":
// Every forty-five minutes
await updateAPI3();
break;
}
console.log("cron processed");
},
};interface Env {}
export default {
async scheduled(
controller: ScheduledController,
env: Env,
ctx: ExecutionContext,
) {
// Write code for updating your API
switch (controller.cron) {
case "*/3 * * * *":
// Every three minutes
await updateAPI();
break;
case "*/10 * * * *":
// Every ten minutes
await updateAPI2();
break;
case "*/45 * * * *":
// Every forty-five minutes
await updateAPI3();
break;
}
console.log("cron processed");
},
};import { Hono } from "hono";
interface Env {}
// Create Hono app
const app = new Hono<{ Bindings: Env }>();
// Regular routes for normal HTTP requests
app.get("/", (c) => c.text("Multiple Cron Trigger Example"));
// Export both the app and a scheduled function
export default {
// The Hono app handles regular HTTP requests
fetch: app.fetch,
// The scheduled function handles Cron triggers
async scheduled(
controller: ScheduledController,
env: Env,
ctx: ExecutionContext,
) {
// Check which cron schedule triggered this execution
switch (controller.cron) {
case "*/3 * * * *":
// Every three minutes
await updateAPI();
break;
case "*/10 * * * *":
// Every ten minutes
await updateAPI2();
break;
case "*/45 * * * *":
// Every forty-five minutes
await updateAPI3();
break;
}
console.log("cron processed");
},
};Тестирование Cron Triggers с помощью Wrangler
Тестировать Cron Triggers рекомендуется с помощью Wrangler.
Cron Triggers можно протестировать с помощью Wrangler, передав --test-scheduled флаг для wrangler dev. Это предоставит /__scheduled (или /cdn-cgi/handler/scheduled для Python Workers) маршрут, который можно использовать для тестирования с помощью HTTP-запроса. Чтобы смоделировать разные варианты cron, cron параметр запроса можно передать.
npx wrangler dev --test-scheduled
curl "http://localhost:8787/__scheduled?cron=*%2F3+*+*+*+*"
curl "http://localhost:8787/cdn-cgi/handler/scheduled?cron=*+*+*+*+*" # Python Workers