The Depot Clock: Tasks, Cron, and runTask
Move the depot forward without a request: defineTask, scheduledTasks, runTask, the Nitro CLI, and Cloudflare Cron Triggers generated from the same config.
A charging depot is a clock. Holds expire, sessions settle, queues move, and totals roll up. None of that should wait for a page view. Stage 6 gives Ampyard a clock.
What it is#
Nitro tasks are named server-side actions. They live in server/tasks/ and can run:
- on demand from a route,
- on a schedule from
scheduledTasks, - from the CLI while the dev server is running,
- from a platform scheduler such as Cloudflare Cron Triggers.
Enable them with two config options:
export default defineConfig({
serverDir: "./server",
experimental: {
tasks: true,
},
});
serverDir is not optional here. Tasks are scanned from the server directory, and nothing is scanned by default.
Why you'd care#
Some work does not belong in a request:
- Expiry. A fifteen-minute hold must end even if no one loads the board.
- Settlement. A session that has been charging for 75 minutes needs a final meter value.
- Rollups. The daily total should exist before the first reader asks for it.
- Simulation. A demo depot needs a clock that moves on its own.
A task is a function with a name, a payload, and a runtime context. The scheduler is configuration. The CLI is how you test it.
What we're building#
Four tasks, but only maintenance is scheduled:
server/tasks/depot/simulate.ts → depot:simulate (manual / ops button)
server/tasks/reservations/expire.ts → reservations:expire
server/tasks/sessions/settle.ts → sessions:settle
server/tasks/depot/rollup.ts → depot:rollup
scheduledTasks: {
"0 0 * * *": ["reservations:expire", "sessions:settle", "depot:rollup"],
},
One nightly maintenance pass releases expired holds, settles idle sessions, and rolls up the day's totals. The simulator is not on a timer; it runs when the ops route calls it or when you invoke it from the CLI.
That is a deliberate budget decision. A one-minute simulator that writes every charging bay's kWh would do roughly 8–10 state writes per tick, which is over 10,000 writes a day. Cloudflare's free KV tier includes only 1,000. The demo uses D1 (100,000 row writes/day) and still refuses to put a clock on a write loop.
Before#
Stage 5 could settle a session, but only when a request asked it to. A hold with no reader stayed held forever.
After#
A task is a small, testable unit:
import { defineTask } from "nitro/task";
import { simulateDepot } from "../../utils/depot";
export default defineTask({
meta: {
name: "depot:simulate",
description: "Advance the virtual charger agents by one tick.",
},
async run() {
return { result: await simulateDepot() };
},
});
The simulator is the interesting one. It reads the live bay state from the active store (D1 by default), settles sessions that reach 72 kWh, promotes the queue when a bay frees, and occasionally takes a connector offline. Notice what it does not do: write kWh on every tick.
if (live.status === "charging") {
const kwh = estimateKwh(stall.powerKw, live.startedAt, live.kwh);
if (kwh >= 72 || Math.random() < 0.02) {
await settleSession(stall.id);
}
continue;
}
estimateKwh derives the delivered energy from startedAt and the bay's power rating:
function estimateKwh(powerKw: number, startedAt: string | undefined, stored = 0): number {
if (!startedAt) return roundKwh(stored);
const elapsedHours = Math.max(0, (Date.now() - Date.parse(startedAt)) / 3_600_000);
return roundKwh(Math.max(stored, Math.min(powerKw * elapsedHours * 0.92, 82)));
}
The board calls the same helper when it builds a snapshot. Charging progress moves on every read, and state is written only when a session starts, settles, or changes state.
A route can run a task without waiting for cron:
import { defineHandler } from "nitro";
import { runTask } from "nitro/task";
import { buildSnapshot } from "../../utils/depot";
export default defineHandler(async () => {
const tick = await runTask("depot:simulate");
return { tick: tick.result, snapshot: await buildSnapshot() };
});
That route is what the Advance depot clock button calls. It is also a warning: runTask from an HTTP route is a privileged action. In a real depot it sits behind operator auth.
The CLI#
While nitro dev is running, the Nitro CLI talks to the dev server:
npx nitro task list
npx nitro task run depot:simulate
npx nitro task run db:migrate --payload '{"force":true}'
The list output includes the meta descriptions. The run output includes the task result. If the dev server is not running, the command cannot reach the task registry.
With the Vite plugin, use vite dev for the app and run the Nitro task commands in a second terminal. The dev server is the registry.
On Cloudflare#
cloudflare_module turns scheduledTasks into Cron Triggers at build time. The generated .output/server/wrangler.json in this repo contains:
{
"triggers": {
"crons": ["0 0 * * *"]
}
}
No manual Wrangler config. The same source that runs setInterval-style cron locally becomes a platform schedule in production.
Cloudflare's minimum granularity is one minute, which is plenty for maintenance. The demo uses a single nightly pass, and the simulator is deliberately not on a platform schedule: it is a demo action, not a production job. Run it from the ops button or the CLI when you want the depot to move.
The write budget#
Cloudflare's free KV tier includes 1,000 writes per day; D1 includes 100,000 row writes per day. A one-minute simulator that writes every charging bay's kWh is roughly 8–10 writes per tick: over 10,000 a day. That is how a KV-backed demo exhausts its tier in under two hours. D1 gives the demo room, but the right design is still to write only when state changes.
The fix is a better state model, not a bigger cache:
- Store
startedAtand the bay'spowerKw; derive kWh when you read. - Write state only when it changes: start, settle, hold, release, queue join/leave.
- Keep one nightly maintenance pass for events that must happen eventually (an expiry, a settlement), not a simulation loop.
- Run the simulator from the ops route so the demo moves when a reader asks it to.
The board still animates: each snapshot recomputes kWh from the clock.
Do it yourself#
Start the app:
pnpm --filter ampyard dev
In a second terminal:
npx nitro task list
npx nitro task run depot:simulate
npx nitro task run reservations:expire
npx nitro task run depot:rollup
Then open /preview/6 and click Advance depot clock. Watch the bay statuses, the queue, and the recent events change.
If you want to see the schedule without waiting, trigger the task route directly:
curl -s -X POST http://localhost:4321/api/ops/tick | jq '.tick'
The live stage#
The preview above is /preview/6. The depot clock panel lists the scheduled tasks, the recent events, and the cache status. The Advance depot clock and Send agent heartbeat buttons are live. The ops page at /ops adds the radio, which is stage 7.
Gotchas#
serverDirmust be set. Without it,server/tasks/is not scanned andrunTaskreturns a 404.- Cron expressions are not a queue.
runTaskdeduplicates by task name: a second call while the first is running shares the first result. That is good for a clock, surprising for a job queue. - One minute is the floor on Cloudflare. If you need faster ticks, run them from a request, a Durable Object alarm, or a queue consumer.
- The free tier is a design constraint. KV's 1,000 writes a day is not a lot; D1's 100,000 is the demo's budget. Never write state on a timer when you can derive it from a timestamp.
runTaskis privileged. Authenticate the route that calls it, or a reader can advance your depot (and your billing) at will.context.waitUntilis not guaranteed. On runtimes that provide it, hand background work to it. On runtimes that do not, await the work.- The dev server owns the registry.
nitro taskcommands do not start a server; they talk to the one that is already running.
Recap#
Ampyard now has a clock: tasks for expiry, settlement, rollups, and simulation; a low-frequency maintenance schedule; runTask for the ops button; and the Nitro CLI for testing. Stage 7 makes the board move without a refresh.
Next: Live: SSE + WebSocket.