Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

複数の Cron Triggers

3 つの異なるスケジュールで複数の Cron Triggers を設定する

最終更新 Markdown で表示Agent セットアップ

すぐに始める場合は、次のボタンをクリックします。

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 フラグを渡すと、Cron Triggers をテストできます。このフラグを付けると、HTTP リクエストでテストできる /cdn-cgi/local/scheduled ルートが公開されます。異なる cron パターンをシミュレートするには、cron クエリパラメーターを渡します。

npx wrangler dev --test-scheduled

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

役に立ちましたか?