Skip to content

Timers

Let an agent schedule deferred wake-up timers for itself instead of polling or running shell sleep commands. Use Timers for one-shot check-ins (“check CI in 5 minutes”) or recurring polls with an optional maximum fire count.

Source

While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy.

Single-run usage

With no registry argument, Timers manages timers inside a single agent.run(). If the model finishes its response while timers are pending, after_node_run waits for the next timer to fire and enqueues a TimerFiredPart so the run continues automatically.

from pydantic_ai import Agent
from pydantic_ai_harness import Timers

agent = Agent('anthropic:claude-opus-5-5', capabilities=[Timers()])
result = agent.run_sync('Check the deployment status in 5 minutes and report back.')
print(result.output)

The capability gives the model three tools:

  • schedule_timer(prompt, delay_seconds=None, interval_seconds=None, max_fires=None) — schedule a one-shot timer (delay_seconds) or a recurring check-in (interval_seconds, with optional initial delay_seconds and max_fires cap).
  • list_timers() — list pending timers for this conversation with their IDs, remaining time, and prompts.
  • cancel_timer(timer_id) — cancel a pending timer by ID.

Multi-turn hosts

In a multi-turn host such as Pax, a timer should outlive the turn that scheduled it so the user stays in control while the timer waits. Create a TimerRegistry owner, open it for the session lifetime, and pass it to Timers(registry=..., conversation_id=...):

from pydantic_ai import Agent
from pydantic_ai_harness import Timers
from pydantic_ai_harness.timers import TimerRegistry


def on_wakeup(conversation_id: str | None) -> None:
    ...  # Trigger an automated turn (`agent.run(None, ...)`) in the host


registry = TimerRegistry(on_wakeup=on_wakeup)


async def run_session() -> None:
    async with registry.opened():
        agent = Agent(
            'anthropic:claude-opus-5-5',
            capabilities=[Timers(registry=registry, conversation_id='conv-1')],
        )
        # Turn 1 ends right away while the timer stays active in `registry`.
        await agent.run('Check CI in 5 minutes.')

When an external TimerRegistry is passed, keep_run_alive defaults to False: the turn finishes cleanly, and when a timer fires between turns TimerRegistry queues its TimerFiredPart and calls on_wakeup(conversation_id). When the host starts the automated wake-up turn (agent.run(None, ...)), Timers automatically enqueues the queued TimerFiredPart with 'asap' priority so it enters the first model request with no synthetic user prompt. If a timer fires while a run is already active, Timers delivers it into that run via ctx.enqueue(..., priority='when_idle'). Cancelling a timer drops any queued or unacknowledged wake-up for it as well.

Wake-up framing

Fired timers are delivered as TimerFiredPart, a capability part on the user channel wrapped in <scheduled_wakeup timer_id="..." fire_count="..." schedule="...">...</scheduled_wakeup> with ModelSource('timers'). Because the model authored the prompt text, it carries no user or application authority and cannot grant tool approval.

Limits, telemetry, and scope

  • max_timers (default 10), max_recurring_fires (default 10, or None for uncapped), min_delay_seconds (default 1.0), and max_delay_seconds (default 86400.0) bound what the model can schedule.
  • Undelivered wake-ups for the same timer coalesce in the pending queue so an inactive conversation cannot accumulate an unbounded backlog.
  • clock and sleep can be injected on Timers or TimerRegistry for deterministic testing without real waits.
  • Timers adds no extra OpenTelemetry spans: core’s instrumentation already spans every tool call (schedule_timer, list_timers, cancel_timer) and every model request, and delivery is observable via EnqueuedMessagesEvent.
  • Timers does not support durable execution because in-process timers are not recorded across replay or process boundaries. Combining it with any durable execution capability raises UserError at agent construction.

API reference

Timers

Bases: AbstractCapability[AgentDepsT]

Let an agent schedule deferred wake-up timers for itself.

Provides schedule_timer, list_timers, and cancel_timer. When a timer fires, the agent receives a TimerFiredPart containing the wake-up prompt.

With no registry argument, timers are scoped to a single agent.run() and after_node_run keeps the run alive while timers are pending so the agent wakes automatically. Pass an opened TimerRegistry to let timers outlive individual turns in a multi-turn host such as Pax.

Attributes

registry

Optional external timer owner for multi-turn hosts. When None, each run owns its own timers.

Type: TimerRegistry | None Default: None

conversation_id

Conversation scope when sharing a TimerRegistry across conversations.

Type: str | None Default: None

keep_run_alive

Whether after_node_run waits for pending timers before ending the run.

Defaults to True when registry is None (single-run mode) and False when an external registry is supplied (multi-turn host mode).

Type: bool | None Default: None

max_timers

Maximum number of concurrent pending timers per conversation.

Type: int Default: 10

max_recurring_fires

Default and maximum repetition cap for recurring timers, or None for unlimited.

Type: int | None Default: 10

min_delay_seconds

Minimum allowed delay or repeat interval, in seconds.

Type: float Default: 1.0

max_delay_seconds

Maximum allowed delay or repeat interval, in seconds.

Type: float Default: 86400.0

clock

Monotonic clock used when creating a run-local TimerRegistry.

Type: Callable[[], float] Default: time.monotonic

sleep

Async sleep function used when creating a run-local TimerRegistry.

Type: Callable[[float], Awaitable[None]] Default: anyio.sleep

Methods

combine

@classmethod

def combine(
    cls,
    capabilities: Sequence[AbstractCapability[AgentDepsT]],
) -> AbstractCapability[AgentDepsT]

Require multiple Timers capabilities under one id to agree.

Returns

AbstractCapability[AgentDepsT]

get_serialization_name

@classmethod

def get_serialization_name(cls) -> str | None

Not spec-serializable: holds live timer state and clock/sleep callables.

Returns

str | None

durable_unsupported_reason
def durable_unsupported_reason(spec: DurabilityEngineSpec) -> str | None

Refuse every durable engine: in-process timers are not recorded across replay or process boundaries.

Returns

str | None

for_run

@async

def for_run(ctx: RunContext[AgentDepsT]) -> Self

Start each run with its own run-local timer binding.

Returns

Self

TimerRegistry

In-process owner for scheduled timers and their pending wake-up messages.

Open with async with registry.opened(): to run timers across multiple turns (as in a host such as Pax). A standalone Timers() without an external TimerRegistry opens a run-local instance automatically.

Attributes

is_open

Whether the timer task group is currently open.

Type: bool

Methods

opened

@async

def opened() -> AsyncGenerator[TimerRegistry]

Run scheduled timers for the lifetime of this context; exiting cancels all pending timers.

Returns

AsyncGenerator[TimerRegistry]

schedule
def schedule(
    *,
    prompt: str,
    delay_seconds: float,
    interval_seconds: float | None = None,
    max_fires: int | None = None,
    conversation_id: str | None = None,
) -> ScheduledTimer

Schedule a new one-shot or recurring timer.

Returns

ScheduledTimer

list_timers
def list_timers(
    *,
    conversation_id: str | None = None,
    all_conversations: bool = False,
) -> tuple[ScheduledTimer, ...]

Return active timers ordered by next fire time.

Returns

tuple[ScheduledTimer, …]

has_active
def has_active(*, conversation_id: str | None = None) -> bool

Whether at least one timer is pending for conversation_id.

Returns

bool

waiting
def waiting(*, conversation_id: str | None = None) -> bool

Whether at least one fired wake-up is queued for conversation_id.

Returns

bool

cancel
def cancel(
    timer_id: str,
    *,
    conversation_id: str | None = None,
    all_conversations: bool = False,
) -> bool

Cancel a pending timer and drop any queued or unacknowledged wake-up for it; returns True if matched.

Returns

bool

cancel_all
def cancel_all(
    *,
    conversation_id: str | None = None,
    all_conversations: bool = False,
) -> int

Cancel all pending timers and drop queued/in-flight wake-ups for conversation_id; returns active timers cancelled.

Returns

int

ScheduledTimer

A pending timer owned by TimerRegistry.

Attributes

id

Short unique timer identifier.

Type: str

prompt

Message delivered to the agent when the timer fires.

Type: str

delay_seconds

Initial delay before the first fire, in seconds.

Type: float

interval_seconds

Repeat interval in seconds for recurring timers, or None for one-shot.

Type: float | None Default: None

max_fires

Maximum number of times a recurring timer fires before stopping, or None for unlimited.

Type: int | None Default: None

created_at

Clock timestamp when the timer was scheduled.

Type: float

next_fire_at

Clock timestamp when the timer will next fire.

Type: float

fire_count

How many times this timer has fired so far.

Type: int Default: 0

conversation_id

Conversation scope for multi-conversation hosts, or None when unscoped.

Type: str | None Default: None

Methods

describe
def describe(*, now: float) -> str

Render a one-line summary of this timer relative to now.

Returns

str

TimerFiredPart

Bases: DataCapabilityPart[str]

A scheduled timer’s wake-up message, delivered when the timer fires.

Data on the user channel in a <scheduled_wakeup> tag naming the timer, with a note that the model scheduled it, not the user or the application.

Attributes

timer_id

The timer’s id.

Type: str

fire_count

How many times this timer has fired, including this wake-up.

Type: int Default: 1

schedule

Whether this timer will fire again on its interval ('recurring') or has completed ('one_shot').

Type: Literal[‘one_shot’, ‘recurring’] Default: 'one_shot'