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

多个 Cron Triggers

Set multiple Cron Triggers on three different schedules.

最后更新 查看 MarkdownAgent 设置

如需快速上手,请点击下方按钮。

部署到 Cloudflare

这会在你的 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");
	},
};

使用 Wrangler 测试 Cron Triggers

测试 Cron Triggers 的推荐方式是使用 Wrangler。

可以在运行 wrangler dev 时传入 --test-scheduled 标志,使用 Wrangler 测试 Cron Triggers。这会开放 /cdn-cgi/local/scheduled 路由,供你通过 HTTP 请求进行测试。要模拟不同的 cron 表达式,可以传入 cron 查询参数。

npx wrangler dev --test-scheduled

curl "http://localhost:8787/cdn-cgi/local/scheduled?cron=*+*+*+*+*" # Python Workers

这篇文档对您有帮助吗?