← Cloudflare Workers / workers / examples
Nastavení Cron Triggers
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
},
};Nastavit Cron Triggers ve Wrangleru
Viz Cron Triggers další informace o tom, jak přidat Cron Trigger.
Pokud nasazujete pomocí Wrangler, nastavte syntaxi cronu (jednou za hodinu podle ukázky níže) přidáním tohoto zápisu do souboru Wrangler:
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "worker",
// ...
"triggers": {
"crons": [
"0 * * * *"
]
}
}"$schema" = "./node_modules/wrangler/config-schema.json"
name = "worker"
[triggers]
crons = [ "0 * * * *" ]Jiný Cron Trigger můžete také nastavit pro každé prostředí ve vašem Konfigurační soubor Wrangler. Musíte vložit [triggers] tabulku ve zvoleném prostředí. Například:
{
"env": {
"dev": {
"triggers": {
"crons": [
"0 * * * *"
]
}
}
}
}[env.dev.triggers]
crons = [ "0 * * * *" ]Testování Cron Triggers pomocí Wrangler
Doporučeným způsobem testování Cron Triggers je použití Wrangler.
Cron Triggers lze otestovat pomocí Wrangleru předáním --test-scheduled příznak pro wrangler dev. Tím se zpřístupní /__scheduled (nebo /cdn-cgi/handler/scheduled pro Python Workers) trasu, kterou lze použít k testování pomocí HTTP požadavku. Chcete-li simulovat různé cron vzory, cron parametr dotazu lze předat.
npx wrangler dev --test-scheduled
curl "http://localhost:8787/__scheduled?cron=0+*+*+*+*"
curl "http://localhost:8787/cdn-cgi/handler/scheduled?cron=*+*+*+*+*" # Python Workers