Most agent tutorials end at a chat box that calls one function. A scheduled agent wakes up on its own, checks conditions, executes tools, writes state, and goes back to sleep. The difference is a timer, a state checkpoint, and idempotency logic.

This article walks through a 150-line implementation that exposes the scheduling primitive itself: how an agent loop decides when to wake up, what state must persist between runs, and how to handle tool failures when no human is watching the console.

The Four-Part Loop

Strip away the vocabulary and an agent is four things in a loop:

  1. A goal written in plain language
  2. A model that reads the goal and history
  3. Tools the model can call (search, fetch, query, send)
  4. A stop condition because loops that never stop cost money

The model does not execute anything. It asks for a tool, your code runs it, and the result goes back into the conversation. Everything else (memory, scheduling, dashboards) is ordinary software wrapped around that loop.

Why Cron Is the Missing Piece

A chat agent only works when a human types. A scheduled agent works on its own. Cron is the simplest way to get there: a line like 0 6 * * 1 means "every Monday at 06:00". When it fires, you start one run of the agent with a stored goal.

Pattern Who decides the schedule Use it for
Human-defined You write the job and its cron string Weekly reports, daily monitoring
Agent-defined The agent calls a schedule_job tool "Check this competitor again in 3 days"

The second pattern is where agents start to feel alive, and it is also where they can hurt you. An agent that schedules itself can create runaway job trees if you do not cap depth or validate intervals.

State Persistence Between Runs

A scheduled agent must remember what it learned. Between runs, you need:

  • Job metadata: goal, cron string, next run time, created timestamp
  • Run history: each execution's start time, end time, status, error message
  • Agent memory: conversation history, tool outputs, decisions made

The simplest schema is two tables:

CREATE TABLE jobs ( id TEXT PRIMARY KEY, goal TEXT NOT NULL, cron_pattern TEXT NOT NULL, next_run TIMESTAMP NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE runs ( id TEXT PRIMARY KEY, job_id TEXT REFERENCES jobs(id), started_at TIMESTAMP NOT NULL, ended_at TIMESTAMP, status TEXT CHECK(status IN ('running', 'success', 'failed')), error TEXT, conversation_log JSONB ); 

The conversation_log column holds the full agent loop: user messages, assistant responses, tool calls, and tool results. This is your replay buffer. If a run fails, you can inspect the exact sequence of tool calls that led to the error.

Tool Invocation Pattern

The agent loop looks like this:

def run_agent(job_id: str, max_iterations: int = 10): job = db.get_job(job_id) run_id = db.create_run(job_id, status='running') messages = [{"role": "user", "content": job.goal}] for i in range(max_iterations): response = llm.chat(messages, tools=TOOL_REGISTRY) messages.append(response.message) if response.finish_reason == 'stop': db.update_run(run_id, status='success', conversation_log=messages) return if response.finish_reason == 'tool_calls': for tool_call in response.tool_calls: result = execute_tool(tool_call.name, tool_call.arguments) messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result) }) else: db.update_run(run_id, status='failed', error='Unexpected finish reason') return db.update_run(run_id, status='failed', error='Max iterations reached') 

The key decisions:

  • Max iterations: Hard cap to prevent runaway loops. Ten is reasonable for most tasks.
  • Tool execution: Synchronous and blocking. If a tool call fails, the whole run fails. You could add retries here.
  • Conversation log: Stored as JSONB so you can query tool call patterns later.

Handling Tool Failures

When a tool call fails in a scheduled system, no human is watching. You have three options:

  1. Fail the run immediately: Simple, but brittle. A single API timeout kills the whole job.
  2. Retry with exponential backoff: Wrap tool execution in a retry loop. Log each attempt.
  3. Return the error to the agent: Let the model see the failure and decide what to do next.

Option three is the most interesting. If a web search times out, the agent can try a different query or skip that step. The error becomes part of the conversation:

def execute_tool(name: str, args: dict) -> dict: try: return TOOL_REGISTRY[name](**args) except Exception as e: return {"error": str(e), "type": type(e).__name__} 

The model sees {"error": "Connection timeout", "type": "RequestException"} and can adapt. This pattern works well for transient failures but not for logic errors in your tool code.

The Scheduler

The scheduler is a loop that checks for jobs whose next_run is in the past:

def scheduler_loop(interval_seconds: int = 60): while True: now = datetime.utcnow() due_jobs = db.get_jobs_due_before(now) for job in due_jobs: try: run_agent(job.id) except Exception as e: db.log_error(job.id, str(e)) finally: next_run = croniter(job.cron_pattern, now).get_next(datetime) db.update_job_next_run(job.id, next_run) time.sleep(interval_seconds) 

This is naive but functional. For production, you want:

  • Distributed locking: Use Redis or Postgres advisory locks so multiple scheduler processes do not run the same job twice.
  • Job priority: Add a priority column and sort by it before next_run.
  • Concurrency limits: Cap how many jobs run in parallel to avoid resource exhaustion.

Agent-Defined Scheduling

The dangerous part: letting the agent create its own jobs. You need a tool like this:

def schedule_job(goal: str, cron_pattern: str, parent_job_id: str = None) -> dict: # Validate cron pattern try: croniter(cron_pattern) except Exception: return {"error": "Invalid cron pattern"} # Prevent runaway recursion if parent_job_id: depth = db.get_job_depth(parent_job_id) if depth >= MAX_JOB_DEPTH: return {"error": "Max job depth exceeded"} # Cap interval to prevent too-frequent jobs interval_seconds = get_cron_interval(cron_pattern) if interval_seconds < MIN_INTERVAL_SECONDS: return {"error": f"Interval must be at least {MIN_INTERVAL_SECONDS}s"} job_id = db.create_job(goal, cron_pattern, parent_job_id) return {"job_id": job_id, "next_run": db.get_job(job_id).next_run} 

The guardrails:

  • Depth limit: Track parent-child relationships. Stop at depth three or four.
  • Interval floor: Do not allow jobs that run more than once per minute.
  • Pattern validation: Reject malformed cron strings before they hit the database.

Without these, an agent can create thousands of jobs in seconds. One user reported an agent that scheduled itself every second to "check for updates", which cost $200 in API calls before they noticed.

Observability Hooks

You need to see what the agent is doing. Add these logging points:

  • Job created: Log goal, cron pattern, parent job ID
  • Run started: Log job ID, run ID, timestamp
  • Tool called: Log tool name, arguments, result, latency
  • Run ended: Log status, error, total duration, iteration count

Store these in a separate events table or ship them to a log aggregator. When a job starts failing, you can trace back through the tool call sequence to find the break.

Deployment Shape

The simplest deployment is a single process running the scheduler loop. For production:

  • Separate scheduler and workers: The scheduler enqueues jobs, workers pull from the queue.
  • Horizontal scaling: Run multiple workers. Use a queue (Redis, RabbitMQ) to distribute jobs.
  • Health checks: Expose an HTTP endpoint that returns the last scheduler tick time. Alert if it stops advancing.

A minimal Docker Compose setup:

services: postgres: image: postgres:15 environment: POSTGRES_DB: agents scheduler: build: . command: python scheduler.py depends_on: - postgres worker: build: . command: python worker.py depends_on: - postgres deploy: replicas: 3 

The scheduler process is a single point of failure. If it dies, no jobs run. Add a supervisor (systemd, Kubernetes liveness probe) to restart it.

Likely Failure Modes

Failure Symptom Fix
Runaway job creation Database fills with jobs, API costs spike Add depth and interval limits to schedule_job
Duplicate runs Same job runs twice at the same time Add distributed locking before run_agent
Lost state Agent forgets previous runs Store conversation log in runs table
Tool timeout Run hangs forever Add timeout to tool execution, return error to agent
Scheduler death Jobs stop running Add health check and supervisor

Technical Verdict

Use scheduled agent loops when:

  • You need agents that work without human input (monitoring, reporting, data collection)
  • The task has a natural cadence (daily, weekly, on-change)
  • You can tolerate eventual consistency (a few minutes of delay is fine)

Avoid when:

  • You need sub-second response times (use event-driven triggers instead)
  • The agent must coordinate with other agents in real time (use a message bus)
  • You cannot afford runaway costs (add strict budget caps and kill switches first)

The 150-line implementation is enough to prove the concept. For production, add distributed locking, observability, and guardrails. The core loop stays the same: wake up, check state, call tools, write results, go back to sleep.

Source Links