跳转到内容
搜索文档

设置 Cron Triggers

使用 Cron Triggers 按计划运行 Worker。

最后更新 查看 MarkdownAgent 设置
export default {
	async scheduled(controller, env, ctx) {
		console.log("cron processed");
	},
};
interface Env {}
export default {
	async scheduled(
		controller: ScheduledController,
		env: Env,
		ctx: ExecutionContext,
	) {
		console.log("cron processed");
	},
};
from workers import WorkerEntrypoint, Response

class Default(WorkerEntrypoint):
    async def scheduled(self, controller, env, ctx):
  			print("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("Hello World!"));

// 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,
	) {
		console.log("cron processed");

		// You could also perform actions like:
		// - Fetching data from external APIs
		// - Updating KV or Durable Object storage
		// - Running maintenance tasks
		// - Sending notifications
	},
};

在 Wrangler 中设置 Cron Triggers

有关如何添加 Cron Trigger 的更多信息,请参阅 Cron Triggers

如果使用 Wrangler 部署,可通过在 Wrangler 文件中添加以下内容来设置 cron 语法(如下所示为每小时一次):

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "worker",
	// ...
	"triggers": {
		"crons": [
			"0 * * * *"
		]
	}
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "worker"

[triggers]
crons = [ "0 * * * *" ]

你也可以在 Wrangler 配置文件中为每个环境设置不同的 Cron Trigger。需要将 [triggers] 表放在所选环境下方。例如:

{
	"env": {
		"dev": {
			"triggers": {
				"crons": [
					"0 * * * *"
				]
			}
		}
	}
}
[env.dev.triggers]
crons = [ "0 * * * *" ]

使用 Wrangler 测试 Cron Triggers

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

可以使用 Wrangler 测试 Cron Triggers:向 wrangler dev 传入 --test-scheduled 标志。这会暴露 /__scheduled(Python Workers 为 /cdn-cgi/handler/scheduled)路由,可通过 HTTP 请求测试。要模拟不同的 cron 模式,可传入 cron 查询参数。

npx wrangler dev --test-scheduled

curl "http://localhost:8787/__scheduled?cron=0+*+*+*+*"

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

这篇文档对您有帮助吗?