Cookbook: Scheduled cron agent
Agent runs on a schedule — hourly, daily, cron expression. Example: a backlog-draft agent that polls the ticket inbox every hour and drafts replies to any unresolved tickets.
| Role | Detail |
|---|---|
| Reads | ctx.capability (tickets.list_unresolved, tickets.get_by_id) |
| Writes | via ctx.human.request() on the drafted reply (reviewer approves before send) |
| State | cursor position via ctx.state so each run only drafts tickets received since the last run |
How the agent works#
Build it#
- Declare the schedule — manifest.json
The key field is
schedules[]. Each entry defines a cron trigger that the platform fires with the entry'sinputpayload asreq.payload.JSON{ "$schema": "https://schemas.konstera.ai/agent-manifest.v3.json", "id": "io.konstera.ticket-backlog-draft", "version": "0.1.0", "name": "Ticket Backlog Draft (Scheduled)", "description": "Hourly: drafts replies to unresolved tickets.", "icon": "⏰", "autonomy": "require_review", "runtime": { "kind": "container", "image": "ghcr.io/your-org/ticket-backlog-draft:0.1.0", "port": 8080, "healthPath": "/health", "timeoutSeconds": 300, "memoryMi": 512, "cpuMillis": 500 }, "input": { "type": "object", "properties": { "mode": { "type": "string", "enum": ["poll", "manual"], "default": "manual" } } }, "schedules": [ { "name": "hourly-backlog", "cron": "0 * * * *", "timezone": "UTC", "input": { "mode": "poll" } } ], "capabilities": { "needs": [ { "name": "tickets.list_unresolved", "required": true, "reason": "Hourly backlog scan — list unresolved tickets since last cursor" }, { "name": "tickets.get_by_id", "required": true, "reason": "Fetch each ticket's full thread for drafting" } ] } }Cron format: standard 5-field (minute, hour, day-of-month, month, day-of-week).
Expression Fires 0 * * * *Top of every hour */15 * * * *Every 15 minutes 0 2 * * *2am daily Timezone: IANA names (
UTC,Europe/London,America/Los_Angeles). - Write the handler — main.py
Load the cursor, fetch tickets since it, draft and park each one, then advance the cursor.
Pythonfrom datetime import datetime, timezone from konstera_sdk import Agent, AgentContext, AgentRequest, AgentResponse, run class BacklogDraftAgent(Agent): """Scheduled: drafts replies to unresolved tickets since last run.""" async def handle( self, req: AgentRequest, ctx: AgentContext ) -> AgentResponse: mode = (req.payload or {}).get("mode", "manual") await ctx.log.info("start", mode=mode, invocation=req.invocation_id) # 1. Load the cursor — last timestamp we processed up to cursor_str = await ctx.state.get("last_processed_at") cursor = ( datetime.fromisoformat(cursor_str) if cursor_str else datetime.now(timezone.utc) ) # 2. Fetch tickets since the cursor tickets = await ctx.capability.call( "tickets.list_unresolved", since_iso=cursor.isoformat(), include_assigned=False, limit=100, ) if not tickets: await ctx.log.info("no_backlog") return AgentResponse( content="No backlog to process.", structured={"drafted": 0, "cursor": cursor.isoformat()}, ) # 3. Draft a reply for each (parallelisation left as an exercise) drafted = 0 for ticket_summary in tickets: ticket = await ctx.capability.call( "tickets.get_by_id", id=ticket_summary["id"] ) if not ticket: continue draft = await self._draft_reply(ticket, ctx) await ctx.human.request( kind="backlog-draft-reply", tier="T1", summary=f"Draft reply for ticket {ticket['id']} ({ticket['subject']})", detail={ "ticket_id": ticket["id"], "subject": ticket["subject"], "customer": ticket.get("customer_email", "unknown"), "draft_reply": draft, }, options=["approve", "reject", "rework"], ) drafted += 1 # 4. Advance the cursor new_cursor = datetime.now(timezone.utc) await ctx.state.set("last_processed_at", new_cursor.isoformat()) await ctx.log.info("done", drafted=drafted, cursor=new_cursor.isoformat()) return AgentResponse( content=f"Drafted {drafted} replies.", structured={ "drafted": drafted, "cursor": new_cursor.isoformat(), "mode": mode, }, ) async def _draft_reply(self, ticket, ctx: AgentContext) -> str: result = await ctx.llm.complete( prompt=( f"Draft a concise, polite reply to this customer ticket:\n\n" f"Subject: {ticket['subject']}\n\n" f"{ticket['body']}" ), system="You draft support replies. Max 3 sentences.", purpose="drafter", max_tokens=256, temperature=0.3, ) return result.content if __name__ == "__main__": run(BacklogDraftAgent()) - Package it — DockerfileDockerfile
FROM python:3.13-slim WORKDIR /app COPY . . RUN pip install --no-cache-dir konstera-sdk==0.6.0 EXPOSE 8080 HEALTHCHECK --interval=10s --timeout=3s --start-period=5s \ CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health', timeout=2)" ENTRYPOINT ["python", "-u", "main.py"]
Testing a schedule locally#
- Invoke the handler with the scheduled payload
Schedules fire from the platform-side Temporal scheduler — so locally you test the agent's
handle()behaviour under the scheduled payload shape by POSTing the equivalent/invokemanually:Terminalcurl -X POST http://localhost:8080/invoke \ -H content-type:application/json \ -d '{"invocationId":"local-1","input":"","payload":{"mode":"poll"},"config":{}}' - Verify the schedule on the deployed instance
To verify the schedule itself fires on the deployed instance, use the portal's Schedules tab — it shows last fire time, next scheduled time, and the trace of each scheduled run.
Agent → Triggers: schedules with cadence, timezone and next fire; webhooks below · example data
Common pitfalls#
| Pitfall | What goes wrong | What to do |
|---|---|---|
| Cursor not persisted on failure | If the agent crashes after processing but before ctx.state.set(), the next run re-processes everything. | Advance the cursor after each ticket, not at the end — idempotency via parent_approval_id on ctx.human.request() prevents duplicate drafts. |
| Overlap on long runs | If a run takes >1h and the schedule fires hourly, two invocations may be in flight. | Use a leader-lock via ctx.state (set a lease, check on entry, exit early if someone else holds it) or lower the schedule frequency. |
| Clock drift | Don't rely on the agent's local clock for cursor positions. | Use the kernel's ctx.tool.call("datetime_now") for a canonical server-time if you need cross-instance consistency. |
schedules[]has the rightcronand an explicit IANAtimezone, and itsinputmatches what the handler branches on.- The handler works when invoked manually as well as on schedule.
- The cursor advances after each ticket, so a crash mid-run doesn't re-process everything.
ctx.human.request()calls are idempotent (parent_approval_id), so a re-run doesn't create duplicate drafts.- Runs can't overlap: a
ctx.statelease, or a schedule interval longer than the slowest run. - Cursor timestamps come from server time (
ctx.tool.call("datetime_now")) if you need cross-instance consistency. - You have tested locally with the
{"mode": "poll"}payload and confirmed fires in the portal's Schedules tab.