Scheduled and Event-Driven Claude Agents: Managed Agents Deployments, Budgets, Outcomes and Webhooks
A SupportDesk agent triages the stale backlog at 6:00 every weekday with nobody watching. Define it once as a Managed Agents deployment (beta) with a cron schedule, an outcome rubric and a 300-cent cap per run, then let a webhook receiver send each ending to the right person: a summary, a page, or a ticket.
What you will learn
- Answer the four questions every unattended agent run needs: trigger, cap, done check, escalation
- Define a scheduled Managed Agents deployment with a cron schedule, an outcome rubric and a per-run budget
- Write a webhook receiver that verifies signatures, drops repeats and fetches the object
- Route each ending of a run to the right person, and never raise the cap automatically
Before you start
- Claude Managed Agents: agents, environments and sessions
- Basic Python
Picture a support agent that triages the stale ticket backlog every weekday morning. Nobody is awake. Nobody is watching. And it still has to behave.
In this article we define that run in code: a schedule, a budget, an outcome and an escalation. The Managed Agents features we use (scheduled deployments, outcomes, budgets and webhooks) are in beta, so names can still change. Check the current docs before you copy a field name into production.
Four questions for a run nobody watches
| Question | Answer |
|---|---|
| When does it start? | A cron schedule |
| How much may one run spend? | A budget on every run |
| How do we know it is done? | An outcome with a rubric |
| Who hears when it is not? | An escalation |
An unattended agent needs all four answers before it runs. Skip one, and the first person to find out is a customer.
Think of a night-shift cleaner in an empty office. An alarm clock wakes them at six: the schedule. A petty-cash envelope pays for supplies, and when it is empty they stop: the budget. The supervisor's checklist says when the job is finished: the outcome. And a phone number on the door is for when something goes wrong: the escalation. A cleaner you can't phone is not unattended. They are lost.
Schedule, event or CI job
There are three ways to start an unattended run:
- On a schedule. A Managed Agents scheduled deployment uses cron. Claude Code has its own scheduled tasks too, in the cloud or on your desktop.
- On an event. A CI failure reaches your handler, and your handler creates a session, or runs Claude Code with the print flag.
- Inside a CI job.
claude --bare -pwith JSON output, a turn limit (--max-turns) and a spend limit (--max-budget-usd).
One thing to remember: a webhook never starts a run. It reports how a run ended.
deployment.py: one create call defines the run
The project runs on a stand-in (the Anthropic SDK on an httpx mock transport, with scripted mornings and signed test webhooks), so no API key is needed and every id, cost and signature is a test value.
"""Define the unattended run once: when it starts, what done means, how much one run may spend."""
from stand_in import AGENT_ID, ENV_ID
CAP_CENTS = "300"
RUBRIC = """# Backlog triage rubric
- Every ticket older than 24 hours has a status note
- Each reply draft names the help article it used
- No email is sent, drafts only
"""
def create(client):
return client.beta.deployments.create(
name="Overnight backlog triage",
agent=AGENT_ID,
environment_id=ENV_ID,
initial_events=[{"type": "user.define_outcome",
"description": "Triage every stale SupportDesk ticket",
"rubric": {"type": "text", "content": RUBRIC},
"max_iterations": 3}],
schedule={"type": "cron", "expression": "0 6 * * 1-5", "timezone": "Europe/London"},
budget={"type": "limit", "max_list_cost": {"amount": CAP_CENTS, "currency": "USD"}},
)
- The schedule: cron with a timezone. Weekdays at 6:00, London time.
- The outcome is the first event. A rubric says what done means, so the agent can't just declare victory. It gets at most three iterations of work and grading.
- The budget is in cents, written as a string. It is copied onto every run, so each morning has its own cap of 300 cents. It is not a total for the whole schedule: a cheap morning doesn't pay for an expensive one.
- These are beta APIs (
client.beta); the SDK sends the beta header for you.
webhook_receiver.py: verify, drop repeats, fetch
"""The listener for the platform's webhooks: verify, drop duplicates, fetch the object, then escalate."""
import standardwebhooks
from stand_in import WEBHOOK_KEY
import escalate
SEEN = set()
def receive(client, delivery):
try:
event = client.beta.webhooks.unwrap(delivery["body"], headers=delivery["headers"], key=WEBHOOK_KEY)
except standardwebhooks.WebhookVerificationError:
return ("reject", "bad signature, dropped")
if event.id in SEEN:
return ("skip", "duplicate event id, discarded")
SEEN.add(event.id)
kind = event.data.type
if kind == "deployment_run.failed":
return escalate.for_failed_run(client.beta.deployment_runs.retrieve(event.data.id))
return escalate.for_session(kind, client.beta.sessions.retrieve(event.data.id))
unwrapchecks the signature and drops anything forged.- A repeated event id is a retry, so it is discarded.
- The event carries only a type and an id, so the receiver fetches the session itself. Events can arrive out of order, so trust the fetched session, not the event.
- A run that never started has its own branch, and fetches the deployment run instead.
escalate.py: one function decides who hears
"""One place that decides who hears about an unattended run, and what they are told."""
def for_session(event_type, s):
"""s is the session fetched from the API: the webhook only carried its id."""
result = s.outcome_evaluations[-1].result
cost, cap = s.usage.list_cost, s.budget.max_list_cost.amount
if event_type == "session.budget_reached":
return ("page", f"at the cap ({cost} of {cap} cents): paused, history kept; raising it is a human call")
if result == "satisfied":
return ("post", f"#support-ops: backlog triaged, cost {cost} cents")
if result == "needs_revision":
return ("wait", "the agent is revising: no one is called yet")
return ("page", f"outcome not met ({result}): session {s.id} kept for review")
def for_failed_run(run):
return ("ticket", f"{run.error.type}: the deployment pauses until someone fixes it")
- At the cap, page a human. Never raise the cap automatically. The session is paused with its history kept, and that paused session is your checkpoint.
- Satisfied is the only finished state. Post a short summary.
- Needs revision means the agent is still working, so nobody is called.
- Anything else, such as
max_iterations_reached, means the outcome was not met. Page, and keep the session for review. - A run that never started opens a ticket.
Four mornings, four endings
run_all.py creates the deployment and replays the scripted mornings of webhooks through the receiver:
deployment depl_test_backlog active: cron 0 6 * * 1-5 Europe/London
each run: outcome with 3 iterations, budget 300 cents
webhooks
mon post #support-ops: backlog triaged, cost 142 cents
mon again skip duplicate event id, discarded
tue wait the agent is revising: no one is called yet
tue page outcome not met (max_iterations_reached): session sesn_tue kept for review
wed page at the cap (312 of 300 cents): paused, history kept; raising it is a human call
thu ticket environment_archived_error: the deployment pauses until someone fixes it
forged reject bad signature, dropped
- Monday ends satisfied at 142 cents. A summary is posted and nobody is woken. The retry of Monday's event is discarded.
- Tuesday needs revision first (wait), then runs out of iterations. That one pages a human.
- Wednesday hits the budget. It pauses just past the cap, at 312 of 300 cents, because the request in flight finishes. A human decides what happens next.
- Thursday never starts: the environment was archived, so a ticket is opened and the deployment pauses until someone fixes it.
- A forged delivery is rejected at the signature check.
Note Wednesday: a cap is not an exact ceiling. Set it with the in-flight request in mind.
Common mistakes
- Raising the cap so the run always finishes. That removes the one safeguard on spend. Page a human instead; the paused session keeps its history.
- Notifying only on success. The runs that need a person are exactly the ones that didn't succeed.
- Retrying until satisfied. The outcome already has
max_iterations. An endless retry is a runaway with a schedule. - Treating a webhook as a trigger, or trusting its payload. It only says something happened. Verify it, drop repeats, and fetch the object.
- Reading the budget as a monthly total. It is a separate cap on every run.
For where the harness and sandbox live, see Claude Managed Agents hosting options. For a chat-side version of the same idea, see Claude scheduled tasks.
Quick recap
| Piece | Setting | In this run |
|---|---|---|
| Schedule | schedule, cron + timezone (beta) | 0 6 * * 1-5 Europe/London |
| Budget | budget.max_list_cost, per run | 300 cents |
| Outcome | user.define_outcome with rubric | 3 iterations; satisfied means done |
| Escalation | webhook, fetch, decide | post, wait, page, ticket |
Try it yourself
Add a Friday where the outcome is satisfied but the cost is 290 cents, close to the cap. Should anyone be told? Decide where that rule belongs, in the rubric, the budget or escalate.py, before you write it.
Related course on Udemy
Claude Certified Developer - Professional (CCDV-P) Exam Prep
Claude agents in production: reliability, observability, evals, cost, guardrails and fleets.View on Udemy ↗: Claude Certified Developer - Professional (CCDV-P) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.
