| 1 | // A cron trigger that records every tick, and a fetch handler that reads the |
| 2 | // record back. |
| 3 | // |
| 4 | // The `scheduled` handler runs in the reserved cron cell's isolate, and a |
| 5 | // `fetch` lands in the stateless Worker pool, so the two never share an |
| 6 | // in-process variable. Writing the tick into a Durable Object is what makes it |
| 7 | // visible to both — and it is the pattern a real cron job wants anyway, since |
| 8 | // only a cell's storage survives the isolate the handler ran in. |
| 9 | // |
| 10 | // Plain Worker code: runs identically on Cloudflare. |
| 11 | export class Ticks { |
| 12 | constructor(state, env) { this.state = state; } |
| 13 | async fetch(request) { |
| 14 | const url = new URL(request.url); |
| 15 | if (url.pathname === "/tick") { |
| 16 | const { cron, scheduledTime } = await request.json(); |
| 17 | const count = ((await this.state.storage.get("count")) ?? 0) + 1; |
| 18 | await this.state.storage.put({ count, lastCron: cron, lastTick: scheduledTime }); |
| 19 | return new Response(null, { status: 204 }); |
| 20 | } |
| 21 | return new Response(JSON.stringify({ |
| 22 | count: (await this.state.storage.get("count")) ?? 0, |
| 23 | lastCron: (await this.state.storage.get("lastCron")) ?? null, |
| 24 | lastTick: (await this.state.storage.get("lastTick")) ?? null, |
| 25 | })); |
| 26 | } |
| 27 | } |
| 28 | const log = (env) => env.TICKS.get(env.TICKS.idFromName("log")); |
| 29 | export default { |
| 30 | async fetch(request, env) { |
| 31 | return log(env).fetch(request); |
| 32 | }, |
| 33 | // Both expressions in wrangler.jsonc arrive here, one call each, and |
| 34 | // `controller.cron` says which one is running. `scheduledTime` is the |
| 35 | // occurrence itself, not the moment this handler started, so a late run |
| 36 | // still records the minute it was scheduled for. |
| 37 | async scheduled(controller, env, ctx) { |
| 38 | await log(env).fetch("http://cron/tick", { |
| 39 | method: "POST", |
| 40 | body: JSON.stringify({ |
| 41 | cron: controller.cron, |
| 42 | scheduledTime: controller.scheduledTime, |
| 43 | }), |
| 44 | }); |
| 45 | }, |
| 46 | }; |