In Cloudflare's Agents SDK, how does this.schedule() send a follow-up two days later, and what happens to it across hibernation and failures?
answer
- number, Date or cron string
- callback is a method name
- rows in SQLite, one alarm
- removed after final failure
- onStart() runs on every wake
basics
~20 sthis.schedule(172800, "sendFollowUp", payload) stores a row in the agent's SQLite and arms its Durable Object alarm, so the agent wakes in two days even with nobody connected. Failed callbacks retry, then a one-time schedule is removed.
solid answer
~40 s`this.schedule(when, callback, payload)` takes a delay in seconds, a `Date` or a cron string, plus the name of a method on the agent and a JSON payload. The SDK writes the task to the `cf_agents_schedules` table and multiplexes all tasks through the Durable Object's single alarm, so the follow-up survives hibernation, eviction and deploys and needs no connected client. When it fires, the callback runs with the payload; if it throws, it is retried (default `maxAttempts: 3`), then the error goes to `onError()` and a one-time schedule is deleted anyway, with no dead-letter store, while cron schedules move to their next run. Watch `onStart()`: it runs on every wake, and delayed or `Date` schedules are not idempotent by default, so pass `{ idempotent: true }` or schedule from the triggering event.
code
typescript · 20 linesimport { Agent, callable } from "agents";
const TWO_DAYS = 2 * 24 * 60 * 60; // seconds
export class SupportAgent extends Agent<Env> {
@callable()
async ticketWentQuiet(ticketId: string) {
const s = await this.schedule(
TWO_DAYS,
"sendFollowUp",
{ ticketId },
{ idempotent: true, retry: { maxAttempts: 5 } },
);
return s.id; // keep it so the customer's reply can cancelSchedule(id)
}
async sendFollowUp(payload: { ticketId: string }) {
// runs two days later, woken by the alarm, with no client connected
}
}go deeper
Recall the three forms of when: seconds, a Date or a cron string, and that the callback is a method name passed as a string.
Explain how schedules are rows in cf_agents_schedules behind one Durable Object alarm, so they survive hibernation and fire with nobody connected.
Show the failure path (retries, onError(), deletion with no dead-letter store) and the duplicate rows that onStart() creates for non-idempotent schedules.
Decide which timed work stays in agent schedules and which moves to a Workflow, by how much retry, visibility and multi-step state the job needs.
## Scheduling inside an agent A support agent often has to act later with nobody connected: send a follow-up two days after a ticket goes quiet, close it after a week, post a daily digest. Cloudflare's Agents SDK does this with **`this.schedule(when, callback, payload?, options?)`**, a method on every `Agent`. - **`when`** decides the mode. A **number** is a delay in **seconds**; a **`Date`** is an exact moment; a **string** is a cron expression for a recurring task. - **`callback`** is the **name of a method** on the agent class, passed as a string. The SDK throws if that method does not exist. - **`payload`** is JSON-serialisable data handed to the callback. - It returns a `Schedule` object whose `id` you can store and later pass to `cancelSchedule(id)`, which resolves to `true` or `false`. | Call | Mode | Runs | | --- | --- | --- | | `this.schedule(172800, "sendFollowUp", { ticketId })` | delayed | once, two days from now | | `this.schedule(new Date("2026-11-02T09:00:00Z"), "sendFollowUp", { ticketId })` | scheduled | once, at that instant | | `this.schedule("0 8 * * 1-5", "digest", {})` | cron | every weekday at 08:00 | | `this.scheduleEvery(90, "poll", {})` | interval | every 90 seconds | Cron precision is one minute; `scheduleEvery()` covers sub-minute or odd intervals and skips a run if the previous one is still going. ## Where the schedule lives A Durable Object has only **one alarm** at a time. The SDK therefore stores every schedule as a row in the agent's SQLite table `cf_agents_schedules` and keeps the single Durable Object alarm set to the earliest due row. When the alarm fires, the runtime wakes the agent, the SDK runs the due callbacks in order, deletes one-time rows, computes the next time for cron and interval rows, and re-arms the alarm. Consequences worth knowing: - The schedule **survives hibernation, eviction and redeploys**, because it is a row on disk, not a timer in memory. - **No client needs to be connected.** The alarm wakes the agent by itself. - **Do not call `ctx.storage.setAlarm()` yourself** in an agent that uses `schedule()`: setting an alarm overrides the one already set, and the SDK is using that single slot for its schedules. - `listSchedules()` and `getScheduleById()` read the table; they are how you show a customer which reminders are pending. ## Failures and retries If a callback throws, the SDK retries it with jittered exponential backoff. The defaults are `maxAttempts: 3`, `baseDelayMs: 100` and `maxDelayMs: 3000`; you can override them per call with `options.retry` or for the class through `static options`. After the last attempt fails, the error is logged and passed to `onError()`, and: 1. a **one-time** schedule is **removed anyway**; 2. a **cron or interval** schedule is **rescheduled** for its next run. There is **no dead-letter store** for schedules. If a failed follow-up must not be lost, record the failure in your own table or reschedule from inside the callback with a longer delay. ## The duplicate trap in `onStart()` `onStart()` runs every time the agent starts: on first creation and after each hibernation or eviction. Scheduling from it is natural, and it is where duplicates come from: - **Cron** schedules are **idempotent by default**: the same cron string, callback and payload return the existing row. - **Delayed and `Date`** schedules are **not** idempotent by default. Each wake inserts another row, so a customer whose agent woke five times gets five follow-ups. - Pass `{ idempotent: true }` to dedupe a one-time schedule on callback plus payload, or schedule the follow-up from the event that starts the timer (the ticket going quiet) rather than from `onStart()`. ## Keeping the agent awake versus scheduling `keepAlive()` and `keepAliveWhile()` hold an alarm-backed heartbeat so that a long piece of work in progress is not evicted mid-flight. They are for work that is already running. A follow-up two days away needs no heartbeat: `schedule()` lets the agent sleep and wakes it on time. ## Schedules, queues and Workflows The SDK offers three ways to run work outside a request, and choosing the right one avoids most scheduling bugs: | Need | Use | | --- | --- | | Run at a future time, once or on a cron | `this.schedule()` | | Run soon, in order, without blocking the response | `this.queue()` | | Many steps, each retried, possibly waiting hours or for an approval | a Workflow started from the agent | A follow-up email is a single step at a known time, so `schedule()` fits. A refund that must call a payment API, wait for a manager's approval and then notify the customer is several dependent steps, which is what a Workflow is for.
- How do you cancel the follow-up when the customer replies first?Store the `id` from the returned `Schedule` (in state or a table) and call `await this.cancelSchedule(id)` when the reply arrives. It resolves to `true` if the row was removed and `false` if it was not found, for example because it already ran.
- When would you choose scheduleEvery() over a cron string?When the period is under a minute or does not fit a cron pattern, such as every 90 seconds. `scheduleEvery()` runs relative to when it was set, skips a run if the previous one is still executing, and is idempotent on callback, interval and payload, so it is safe in `onStart()`.
- Passing milliseconds to this.schedule() when a number means seconds.
- Calling ctx.storage.setAlarm() directly in an agent that also uses schedule().
- Expecting a failed one-time schedule to wait in a dead-letter queue.
- Scheduling a delayed follow-up in onStart() without idempotent: true.
- Holding keepAlive() for two days to wait for a follow-up.