# How AI Agents Run Themselves: Build a Scheduled Agentic System

> Source: <https://dev.to/akumagg/how-ai-agents-run-themselves-build-a-scheduled-agentic-system-ekc>
> Published: 2026-11-23 18:41:29+00:00

**Recommendation:** Give scheduled agents a fixed tool allowlist and persist each tool call to a findings table so runs are auditable and memory notes prevent repeated work.
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>

A working, minimal agent in about 150 lines. No framework, no magic. Just a loop, a few tools, a scheduler and a database.

Most "AI agent" tutorials stop at a chat box that calls one function. That is a demo, not a system. A real agent does work while you sleep: it wakes up on a schedule, looks at the world, decides what to do, writes down what it learned, and tells you the result.

This article builds exactly that, from scratch, in Python. By the end you will have:

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

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

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.

There are two ways to schedule:

| 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. We will add it with guardrails near the end.

Build the data layer before the agent. It is what turns a clever script into a system you can trust.

Four tables are enough:

`jobs`: the goal and the cron string.` runs`: one row per execution, with status and summary.` findings`: every tool call and its raw result, stored as JSON.` memory`: small key/value notes the agent writes for its future self.
Findings are a **log**, memory is a **notebook**. The log is for you when something breaks. The notebook is for the agent so next week's run does not repeat last week's work.

``` python
# db.py
import sqlite3

DB = sqlite3.connect("agent.db", check_same_thread=False)
DB.row_factory = sqlite3.Row
DB.executescript("""
CREATE TABLE IF NOT EXISTS jobs(
  id INTEGER PRIMARY KEY, name TEXT UNIQUE, goal TEXT NOT NULL,
  cron TEXT NOT NULL, enabled INTEGER DEFAULT 1);
CREATE TABLE IF NOT EXISTS runs(
  id INTEGER PRIMARY KEY, job_id INTEGER, started REAL,
  status TEXT, summary TEXT);
CREATE TABLE IF NOT EXISTS findings(
  id INTEGER PRIMARY KEY, run_id INTEGER, tool TEXT,
  data TEXT, created REAL);
CREATE TABLE IF NOT EXISTS memory(
  job_id INTEGER, key TEXT, value TEXT, PRIMARY KEY(job_id, key));
""")
DB.commit()
```

SQLite is fine for one machine. The schema is plain enough to move to Postgres later without changing a line of agent code.

Tools are just functions. The agent never touches the network directly; it can only do what these functions allow. That is your safety boundary.

I use three kinds of data here:

``` python
# tools.py
import os, requests

KEIRO_BASE = os.environ["KEIRO_BASE_URL"]      # copy from your KeiroLabs dashboard
KEIRO_KEY = os.environ["KEIRO_API_KEY"]

def _keiro(path, payload):
    r = requests.post(f"{KEIRO_BASE}{path}", json=payload, timeout=60,
                      headers={"Authorization": f"Bearer {KEIRO_KEY}"})
    r.raise_for_status()
    return r.json()

def web_search(query: str):
    return _keiro("/search", {"query": query})

def extract_url(url: str):
    return _keiro("/extract", {"url": url})

def keyword_volume(keywords: list[str]):
    r = requests.post(
        "https://api.dataforseo.com/v3/keywords_data/google_ads/search_volume/live",
        auth=(os.environ["DFS_LOGIN"], os.environ["DFS_PASSWORD"]), timeout=60,
        json=[{"keywords": keywords[:20], "location_code": 2840, "language_code": "en"}])
    r.raise_for_status()
    return r.json()
```

Endpoint paths and request fields differ by provider and plan. Check each provider's docs and adjust the three small functions above. The rest of the system does not care how they work inside.

Now the heart. The model gets the goal, last time's memory, and a list of tools described as JSON schemas. Each turn it either asks for a tool or gives a final answer.

``` python
# agent.py
import json, time, anthropic
from db import DB
import tools

client = anthropic.Anthropic()
MODEL = "claude-sonnet-5-5"
MAX_STEPS = 8

TOOL_SPECS = [
  {"name": "web_search", "description": "Search the live web.",
   "input_schema": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}},
  {"name": "extract_url", "description": "Read a page as clean text.",
   "input_schema": {"type": "object", "properties": {"url": {"type": "string"}}, "required": ["url"]}},
  {"name": "keyword_volume", "description": "Monthly search volume for keywords.",
   "input_schema": {"type": "object", "properties": {"keywords": {"type": "array", "items": {"type": "string"}}}, "required": ["keywords"]}},
  {"name": "remember", "description": "Save a short note for the next run.",
   "input_schema": {"type": "object", "properties": {"key": {"type": "string"}, "value": {"type": "string"}}, "required": ["key", "value"]}},
]

def run_job(job_id: int):
    job = DB.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone()
    run_id = DB.execute("INSERT INTO runs(job_id, started, status) VALUES(?,?,?)",
                        (job_id, time.time(), "running")).lastrowid
    DB.commit()

    notes = {r["key"]: r["value"] for r in
             DB.execute("SELECT key, value FROM memory WHERE job_id=?", (job_id,))}

    def remember(key, value):
        DB.execute("INSERT OR REPLACE INTO memory VALUES(?,?,?)", (job_id, key, value))
        return "saved"

    handlers = {"web_search": tools.web_search, "extract_url": tools.extract_url,
                "keyword_volume": tools.keyword_volume, "remember": remember}

    messages = [{"role": "user", "content":
        f"Goal: {job['goal']}\n\nYour notes from earlier runs: {json.dumps(notes)}\n"
        "Use tools to research, then write the final report."}]
    summary, status = "", "done"

    try:
        for _ in range(MAX_STEPS):
            resp = client.messages.create(
                model=MODEL, max_tokens=2000, tools=TOOL_SPECS, messages=messages,
                system="You are a careful research agent. Prefer few, targeted tool calls.")
            messages.append({"role": "assistant", "content": resp.content})

            if resp.stop_reason != "tool_use":
                summary = "".join(b.text for b in resp.content if b.type == "text")
                break

            results = []
            for b in resp.content:
                if b.type != "tool_use":
                    continue
                try:
                    out = handlers<a href="**b.input">b.name</a>
                except Exception as e:                      # a failing tool must not kill the run
                    out = {"error": str(e)}
                DB.execute("INSERT INTO findings(run_id, tool, data, created) VALUES(?,?,?,?)",
                           (run_id, b.name, json.dumps({"in": b.input, "out": out})[:100000], time.time()))
                results.append({"type": "tool_result", "tool_use_id": b.id,
                                "content": json.dumps(out)[:8000]})
            messages.append({"role": "user", "content": results})
        else:
            status, summary = "stopped", "Hit the step limit before finishing."
    except Exception as e:
        status, summary = "failed", str(e)

    DB.execute("UPDATE runs SET status=?, summary=? WHERE id=?", (status, summary, run_id))
    DB.commit()
    return summary
```

Three details matter more than they look:

`MAX_STEPS`
Here is what a single weekly run actually does.

The agent reads memory, searches, extracts the best sources, checks keyword demand, writes a brief, then saves notes and sends the result. Nothing in that chain is hard-coded. The goal says "weekly SEO brief on AI search APIs"; the model decides the queries and which pages deserve a full read.

Now make it run by itself. APScheduler reads cron strings straight from the `jobs` table.

``` python
# scheduler.py
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
from db import DB
from agent import run_job

sched = BlockingScheduler()

def sync_jobs():
    sched.remove_all_jobs()
    sched.add_job(sync_jobs, "interval", minutes=1, id="__sync__")   # pick up new jobs
    for j in DB.execute("SELECT * FROM jobs WHERE enabled=1"):
        sched.add_job(run_job, CronTrigger.from_crontab(j["cron"]),
                      args=[j["id"]], id=f"job-{j['id']}",
                      max_instances=1, coalesce=True)

DB.execute("INSERT OR IGNORE INTO jobs(name, goal, cron) VALUES(?,?,?)",
  ("seo-brief", "Write a weekly SEO brief on AI search APIs: new sources, "
   "top keywords with volume, and three article ideas.", "0 6 * * 1"))
DB.commit()

sync_jobs()
sched.start()
```

Because jobs live in the database, adding a new automation is one `INSERT`, not a redeploy. `max_instances=1` stops a slow run from overlapping with the next one.

**No server of your own?** Use the platform's cron instead. GitHub Actions `schedule:`, a system `crontab`, or an external ticker hitting a protected URL all work. Point any of them at `run_job(job_id)`. The agent does not care what pulled the trigger.

This is the step that makes it feel like an agent rather than a script. Add one more tool:

``` python
def schedule_job(name: str, goal: str, cron: str):
    from apscheduler.triggers.cron import CronTrigger
    CronTrigger.from_crontab(cron)                     # raises if invalid
    count = DB.execute("SELECT COUNT(*) FROM jobs").fetchone()[0]
    if count >= 20:
        return {"error": "job limit reached"}
    if cron.split()[0].startswith("*"):                # no "every minute" jobs
        return {"error": "minimum interval is hourly"}
    DB.execute("INSERT OR IGNORE INTO jobs(name, goal, cron, enabled) VALUES(?,?,?,0)",
               (name, goal, cron))                     # created disabled
    DB.commit()
    return {"status": "pending human approval"}
```

Give the model the matching tool spec, and a prompt line such as "If something needs a follow-up, propose a job with `schedule_job`." Now a run can say "this competitor changed pricing, check again in three days" and create that job itself.

The guardrails are not optional:

`enabled` to 1. Once you trust the pattern, you can auto-approve a narrow safe subset.
Treat the agent like a new teammate: it can propose, and you approve until it has earned trust.

A few habits separate a toy from something you leave running:

`failed` and `stopped` runs`send_slack` tool so the final report lands where your team already looks.
An agentic system is not a smarter model. It is a loop plus tools plus a scheduler plus a database. The model supplies judgment, the data layer supplies memory and accountability, and cron supplies the heartbeat. Build those four pieces, keep the guardrails tight, and you have something that quietly does useful work every week.

*If you build this, start with one job and one tool, and run it by hand twice before you schedule it. Your first version will teach you more than any diagram.*
