Skip to content
AnswerWell geo Documentation

Research · 9 min read · Answerwell

Scheduled Tasks, queue() Deferral and Cron Execution

How Cloudflare Agents schedule(), scheduleEvery(), and queue() run delayed, recurring, and background work with persistence and idempotency.

This page summarizes Cloudflare Agents documentation on running work later or in the background: the Agent class schedule() and scheduleEvery() APIs, the built-in queue() task queue, and declarative schedules on the Think harness via getScheduledTasks(). It also notes how these differ from Think Workflows and from in-request timers on Workers (scheduler.wait(), setTimeout()).

schedule() and queue(): when to defer work vs run it on a clock

Section titled “schedule() and queue(): when to defer work vs run it on a clock”

Agents need two different shapes of “run this later”: as soon as possible in order (background after a fast HTTP or chat reply) and at a specific time or on a repeat (cron digests, polling, reminders). Cloudflare maps the first to queue() and the second to schedule() / scheduleEvery(), both backed by SQLite on the Durable Object and surviving restarts.

Use queue when you want tasks to execute as soon as possible in order. Use schedule when you need tasks to run at specific times or on a recurring basis.

— Cloudflare, Queue tasks

Feature queue() schedule() / scheduleEvery() Workflows
When Immediately (FIFO) Future time or recurring Future time, multi-step
Execution Sequential At scheduled time Multi-step with waits
Retries Built-in Built-in Automatic
Persistence cf_agents_queues cf_agents_schedules Workflow engine
Recurring No Yes (cron / interval) No (use scheduling)
Complex logic / human approval No No Yes

Use Queue tasks when the caller should not wait (webhooks, chat handlers). Use Schedule tasks for delays, wall-clock triggers, or cron. Use Think Workflows when the process has several deterministic steps, long waits (for example timeout: "3 days" on step.prompt()), or approval gates—not for a single method callback.

queue(): how to run background work without blocking the response

Section titled “queue(): how to run background work without blocking the response”

queue() adds a row to the agent queue; the runtime flushes tasks in FIFO order, one at a time, in the same agent context as the request that enqueued them.

The Agents SDK provides a built-in queue system that allows you to schedule tasks for asynchronous execution. This is useful for background processing, delayed operations, and managing workloads that do not need immediate execution.

— Cloudflare, Queue tasks

You can use .queue() to enqueue background work — ideal for tasks like processing user messages, sending notifications etc.

— Cloudflare, Agents SDK adds MCP Elicitation support…

queue() API: enqueue, inspect, and remove tasks

Section titled “queue() API: enqueue, inspect, and remove tasks”

Call await this.queue(callback, payload, options?) where callback is a method name on your Agent. Helpers include dequeue, dequeueAll, getQueue, and getQueues (Agent class internals, Queue tasks).

Callback methods should match:

async callbackMethod(payload: unknown, queueItem: QueueItem): Promise<void>

Behavior that surprises people: queuing does not block the caller; the next queued callback does not start until the previous one finishes (changelog example). Tasks are stored in cf_agents_queues, survive restarts, and successful runs are removed automatically (How queue processing works).

Limits (Queue tasks): sequential only, no priority beyond FIFO, processing happens during agent execution—not as separate background jobs. Keep payloads small (JSON in SQLite); design callbacks to be idempotent because retries use exponential backoff when configured (Retries).

schedule(): delayed runs, fixed dates, and cron expressions

Section titled “schedule(): delayed runs, fixed dates, and cron expressions”

schedule() persists a future invocation of any Agent method—same capabilities as a user-driven request (Schedule tasks).

Schedule tasks to run in the future — whether that is seconds from now, at a specific date/time, or on a recurring cron schedule. Scheduled tasks survive agent restarts and are persisted to SQLite.

— Cloudflare, Schedule tasks

Under the hood, scheduling uses Durable Object alarms; because only one alarm exists per object, the Agent class stores multiple schedules in SQL and drives a single alarm (Agent class internals).

schedule() modes: delay, Date, and cron string

Section titled “schedule() modes: delay, Date, and cron string”
Mode Syntax Typical use
Delayed this.schedule(60, ...) — seconds Debounce, follow-ups, polling backoff
Scheduled this.schedule(new Date(...), ...) Appointments, deadlines
Cron this.schedule("0 8 * * *", ...) Daily digests, hourly checks
Interval this.scheduleEvery(30, ...) Sub-minute or odd intervals

Cron uses five fields: minute hour day month weekday (Schedule tasks: Recurring (cron)). Cron precision is minute-level; minimum delay for delayed schedules is 0 (next alarm tick). Each task including payload can be up to 2MB; practical row counts are on the order of tens of thousands per agent (Limits).

scheduleEvery(): fixed intervals with overlap prevention

Section titled “scheduleEvery(): fixed intervals with overlap prevention”

scheduleEvery(intervalSeconds, callback, payload) repeats every N seconds (not milliseconds—contrast the mistaken 5 * 60 * 1000 example in some changelog snippets with the canonical Schedule tasks: Interval API).

The new scheduleEvery() method enables fixed-interval recurring tasks with built-in overlap prevention

— Cloudflare, Agents SDK v0.3.7: Workflows integration…

Compared to cron: intervals support second granularity and arbitrary durations (for example every 90 seconds). If a run is still executing when the next tick is due, the next run is skipped (not queued), with a log warning—unlike cron, which has no built-in overlap prevention (Schedule tasks: Interval). The first execution happens after intervalSeconds, not immediately.

schedule() idempotency: safe cron in onStart()

Section titled “schedule() idempotency: safe cron in onStart()”

Cron schedules are idempotent by default — calling schedule() with the same cron expression, callback, and payload multiple times returns the existing schedule instead of creating a duplicate. This makes cron schedules safe to set up in onStart().

— Cloudflare, Schedule tasks: Recurring (cron)

scheduleEvery() is similarly idempotent on callback + interval + payload (Schedule tasks: Interval). For one-shot delays or Date schedules, pass { idempotent: true } when registering in onStart() so Durable Object restarts do not multiply rows (schedule() options). Cron schedules from autonomous responses illustrate calling await this.schedule("0 9 * * *", "dailyDigest") in onStart() without duplicating work.

Use listSchedules, getScheduleById, and cancelSchedule to inspect or revoke work (Schedule tasks). For dynamic polling (backoff per attempt), reschedule from inside the callback—see Long-running agents: polling with schedule and Rescheduling from callbacks.

Autonomous model calls and chat digests on a schedule

Section titled “Autonomous model calls and chat digests on a schedule”

Agents can invoke models without a live user message by scheduling a method that calls Workers AI or the AI SDK—nightly summaries, classification, monitoring (Calling LLMs: Autonomous model calls).

Agents do not need a user request to call a model. You can schedule model calls to run in the background — for nightly summarization, periodic classification, monitoring, or any task that should happen without human interaction.

— Cloudflare, Calling LLMs

Autonomous responses combine cron schedule() with saveMessages() and waitUntilStable() so a digest runs only when the conversation is quiescent. You can pair schedule() with chat primitives, queue() with deferred saveMessages, or runWorkflow() for multi-step flows (Combining with other Agent primitives).

Think getScheduledTasks(): declarative timezone-aware schedules

Section titled “Think getScheduledTasks(): declarative timezone-aware schedules”

On the Think harness, recurring prompt turns or handler jobs are declared in getScheduledTasks() with a small DSL (Scheduled tasks).

Declare recurring, timezone-aware prompts and handlers with a typed domain-specific language (DSL). Think reconciles the declarations on startup and re-arms the next occurrence after each run, backed by durable idempotent submissions.

— Cloudflare, Agents SDK v0.14.0

Each task must define exactly one of prompt (durable submission via submitMessages()) or handler (app-owned work, often creating a Workflow with idempotencyKey). Wall-clock schedules need a timezone inline, per-task, or via getDefaultTimezone(). If an alarm is late, Think runs the intended occurrence once and schedules the next future slot—it does not backfill missed runs (Scheduled tasks).

For multi-step jobs with approvals, use a handler that starts ThinkWorkflow rather than a long prompt chain (When to use a workflow instead).

Natural-language scheduling into schedule() parameters can use getSchedulePrompt() and scheduleSchema from agents/schedules/parser (Schedule tasks: getSchedulePrompt()).

In-request timers on Workers (not durable agent schedules)

Section titled “In-request timers on Workers (not durable agent schedules)”

Inside a single Worker request context, setTimeout(), setInterval(), and scheduler.wait() delay code in-process. They do not replace Agent schedule() persistence across isolates or restarts.

Timers are only available inside of the Request Context.

— Cloudflare, Web standards: Timers

scheduler.wait() returns a Promise that resolves after a given number of milliseconds. It is an await-able alternative to setTimeout() that does not require a callback.

— Cloudflare, Scheduler

In production, scheduler.wait() does not advance during CPU-only execution (Spectre mitigation); local dev behaves differently (Scheduler: Background). With Node compatibility, node:timers exposes familiar setTimeout / setInterval / setImmediate in that same ephemeral context.

Browser-style timers from the HTML standard (setTimeout / setInterval) are for documents and event loops on the web platform; they do not guarantee exact timing under load (WHATWG: 8.7 Timers). Agent schedule() / queue() are the durable choice for server-side agents on Cloudflare.

The Container class also exposes schedule(when, callback, payload) on top of alarms; documentation warns not to override alarm() directly because the Container manages lifecycle via that hook (Container class: schedule).

Subscribe to diagnostics channels for schedule:* and queue:* events (create, execute, cancel, retry, error, duplicate_warning) when debugging timing or duplicate registration (Schedule and queue events).

Mistake What goes wrong What to do instead
Heavy work inline on webhooks Timeouts from the provider queue() or submitMessages() with idempotencyKey (Webhooks)
schedule(3600, ...) in onStart() without idempotency New row every DO wake { idempotent: true } or cron / scheduleEvery() defaults (Schedule tasks)
Expect parallel queue workers Backlog stalls behind one slow task Split agents or use Workflows for parallel steps (Scheduling vs Queue vs Workflows)
Sub-minute repeat via cron only Cron is minute-granularity scheduleEvery(seconds, ...) (Interval)
Long job + tight scheduleEvery Skipped ticks, warning logs Lengthen interval or shorten callback (Overlap prevention)
Wrong scheduleEvery argument order in old snippets Method never runs on expected cadence Follow scheduleEvery(): seconds, then method name
  1. Deploy the agent and trigger the code path that calls queue() or schedule(); confirm tasks are created using Queue tasks and Schedule tasks patterns in your project (for example from Add to existing project or Quick start).

  2. Inspect pending work with getQueues / listSchedules as documented on Queue tasks and Schedule tasks.

  3. Watch runtime behavior through Schedule and queue events (schedule:execute, queue:error, schedule:duplicate_warning, and related types).

  4. For Think declarative jobs, verify reconciliation and the next occurrence after a run using Scheduled tasks (timezone, handler vs prompt, and idempotency keys).

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page does not match your experience or the linked Cloudflare docs, email yimasynthetic@gmail.com with the page URL and the exact sentence you believe is wrong so it can be corrected.