{"slug": "how-ai-agents-run-themselves-build-a-scheduled-agentic-system", "title": "How AI Agents Run Themselves: Build a Scheduled Agentic System", "summary": "A developer published a from-scratch Python tutorial for building a scheduled agentic system in roughly 150 lines, using a plain model-tool loop, cron scheduling, and a four-table SQLite database (jobs, runs, findings, memory) instead of an agent framework. The design separates human-defined cron jobs from agent-defined scheduling via a schedule_job tool, and confines the agent's network access to a small set of wrapped tool functions that act as its safety boundary.", "body_md": "A working, minimal agent in about 150 lines. No framework, no magic. Just a loop, a few tools, a scheduler and a database.\n\nMost \"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.\n\nThis article builds exactly that, from scratch, in Python. By the end you will have:\n\nStrip away the vocabulary and an agent is four things in a loop:\n\nThe 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.\n\nA 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.\n\nThere are two ways to schedule:\n\n| Pattern | Who decides the schedule | Use it for | \n|---|---|---|\n| **Human-defined** | You write the job and its cron string | Weekly reports, daily monitoring | \n| **Agent-defined** | The agent calls a `schedule_job` tool | \"Check this competitor again in 3 days\" | \n\nThe 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.\n\nBuild the data layer before the agent. It is what turns a clever script into a system you can trust.\n\nFour tables are enough:\n\n`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.\nFindings 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.\n\n``` python\n# db.py\nimport sqlite3\n\nDB = sqlite3.connect(\"agent.db\", check_same_thread=False)\nDB.row_factory = sqlite3.Row\nDB.executescript(\"\"\"\nCREATE TABLE IF NOT EXISTS jobs(\n  id INTEGER PRIMARY KEY, name TEXT UNIQUE, goal TEXT NOT NULL,\n  cron TEXT NOT NULL, enabled INTEGER DEFAULT 1);\nCREATE TABLE IF NOT EXISTS runs(\n  id INTEGER PRIMARY KEY, job_id INTEGER, started REAL,\n  status TEXT, summary TEXT);\nCREATE TABLE IF NOT EXISTS findings(\n  id INTEGER PRIMARY KEY, run_id INTEGER, tool TEXT,\n  data TEXT, created REAL);\nCREATE TABLE IF NOT EXISTS memory(\n  job_id INTEGER, key TEXT, value TEXT, PRIMARY KEY(job_id, key));\n\"\"\")\nDB.commit()\n```\n\nSQLite is fine for one machine. The schema is plain enough to move to Postgres later without changing a line of agent code.\n\nTools are just functions. The agent never touches the network directly; it can only do what these functions allow. That is your safety boundary.\n\nI use three kinds of data here:\n\n``` python\n# tools.py\nimport os, requests\n\nKEIRO_BASE = os.environ[\"KEIRO_BASE_URL\"]      # copy from your KeiroLabs dashboard\nKEIRO_KEY = os.environ[\"KEIRO_API_KEY\"]\n\ndef _keiro(path, payload):\n    r = requests.post(f\"{KEIRO_BASE}{path}\", json=payload, timeout=60,\n                      headers={\"Authorization\": f\"Bearer {KEIRO_KEY}\"})\n    r.raise_for_status()\n    return r.json()\n\ndef web_search(query: str):\n    return _keiro(\"/search\", {\"query\": query})\n\ndef extract_url(url: str):\n    return _keiro(\"/extract\", {\"url\": url})\n\ndef keyword_volume(keywords: list[str]):\n    r = requests.post(\n        \"https://api.dataforseo.com/v3/keywords_data/google_ads/search_volume/live\",\n        auth=(os.environ[\"DFS_LOGIN\"], os.environ[\"DFS_PASSWORD\"]), timeout=60,\n        json=[{\"keywords\": keywords[:20], \"location_code\": 2840, \"language_code\": \"en\"}])\n    r.raise_for_status()\n    return r.json()\n```\n\nEndpoint 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.\n\nNow 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.\n\n``` python\n# agent.py\nimport json, time, anthropic\nfrom db import DB\nimport tools\n\nclient = anthropic.Anthropic()\nMODEL = \"claude-sonnet-5-5\"\nMAX_STEPS = 8\n\nTOOL_SPECS = [\n  {\"name\": \"web_search\", \"description\": \"Search the live web.\",\n   \"input_schema\": {\"type\": \"object\", \"properties\": {\"query\": {\"type\": \"string\"}}, \"required\": [\"query\"]}},\n  {\"name\": \"extract_url\", \"description\": \"Read a page as clean text.\",\n   \"input_schema\": {\"type\": \"object\", \"properties\": {\"url\": {\"type\": \"string\"}}, \"required\": [\"url\"]}},\n  {\"name\": \"keyword_volume\", \"description\": \"Monthly search volume for keywords.\",\n   \"input_schema\": {\"type\": \"object\", \"properties\": {\"keywords\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}}, \"required\": [\"keywords\"]}},\n  {\"name\": \"remember\", \"description\": \"Save a short note for the next run.\",\n   \"input_schema\": {\"type\": \"object\", \"properties\": {\"key\": {\"type\": \"string\"}, \"value\": {\"type\": \"string\"}}, \"required\": [\"key\", \"value\"]}},\n]\n\ndef run_job(job_id: int):\n    job = DB.execute(\"SELECT * FROM jobs WHERE id=?\", (job_id,)).fetchone()\n    run_id = DB.execute(\"INSERT INTO runs(job_id, started, status) VALUES(?,?,?)\",\n                        (job_id, time.time(), \"running\")).lastrowid\n    DB.commit()\n\n    notes = {r[\"key\"]: r[\"value\"] for r in\n             DB.execute(\"SELECT key, value FROM memory WHERE job_id=?\", (job_id,))}\n\n    def remember(key, value):\n        DB.execute(\"INSERT OR REPLACE INTO memory VALUES(?,?,?)\", (job_id, key, value))\n        return \"saved\"\n\n    handlers = {\"web_search\": tools.web_search, \"extract_url\": tools.extract_url,\n                \"keyword_volume\": tools.keyword_volume, \"remember\": remember}\n\n    messages = [{\"role\": \"user\", \"content\":\n        f\"Goal: {job['goal']}\\n\\nYour notes from earlier runs: {json.dumps(notes)}\\n\"\n        \"Use tools to research, then write the final report.\"}]\n    summary, status = \"\", \"done\"\n\n    try:\n        for _ in range(MAX_STEPS):\n            resp = client.messages.create(\n                model=MODEL, max_tokens=2000, tools=TOOL_SPECS, messages=messages,\n                system=\"You are a careful research agent. Prefer few, targeted tool calls.\")\n            messages.append({\"role\": \"assistant\", \"content\": resp.content})\n\n            if resp.stop_reason != \"tool_use\":\n                summary = \"\".join(b.text for b in resp.content if b.type == \"text\")\n                break\n\n            results = []\n            for b in resp.content:\n                if b.type != \"tool_use\":\n                    continue\n                try:\n                    out = handlers<a href=\"**b.input\">b.name</a>\n                except Exception as e:                      # a failing tool must not kill the run\n                    out = {\"error\": str(e)}\n                DB.execute(\"INSERT INTO findings(run_id, tool, data, created) VALUES(?,?,?,?)\",\n                           (run_id, b.name, json.dumps({\"in\": b.input, \"out\": out})[:100000], time.time()))\n                results.append({\"type\": \"tool_result\", \"tool_use_id\": b.id,\n                                \"content\": json.dumps(out)[:8000]})\n            messages.append({\"role\": \"user\", \"content\": results})\n        else:\n            status, summary = \"stopped\", \"Hit the step limit before finishing.\"\n    except Exception as e:\n        status, summary = \"failed\", str(e)\n\n    DB.execute(\"UPDATE runs SET status=?, summary=? WHERE id=?\", (status, summary, run_id))\n    DB.commit()\n    return summary\n```\n\nThree details matter more than they look:\n\n`MAX_STEPS`\nHere is what a single weekly run actually does.\n\nThe 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.\n\nNow make it run by itself. APScheduler reads cron strings straight from the `jobs` table.\n\n``` python\n# scheduler.py\nfrom apscheduler.schedulers.blocking import BlockingScheduler\nfrom apscheduler.triggers.cron import CronTrigger\nfrom db import DB\nfrom agent import run_job\n\nsched = BlockingScheduler()\n\ndef sync_jobs():\n    sched.remove_all_jobs()\n    sched.add_job(sync_jobs, \"interval\", minutes=1, id=\"__sync__\")   # pick up new jobs\n    for j in DB.execute(\"SELECT * FROM jobs WHERE enabled=1\"):\n        sched.add_job(run_job, CronTrigger.from_crontab(j[\"cron\"]),\n                      args=[j[\"id\"]], id=f\"job-{j['id']}\",\n                      max_instances=1, coalesce=True)\n\nDB.execute(\"INSERT OR IGNORE INTO jobs(name, goal, cron) VALUES(?,?,?)\",\n  (\"seo-brief\", \"Write a weekly SEO brief on AI search APIs: new sources, \"\n   \"top keywords with volume, and three article ideas.\", \"0 6 * * 1\"))\nDB.commit()\n\nsync_jobs()\nsched.start()\n```\n\nBecause 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.\n\n**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.\n\nThis is the step that makes it feel like an agent rather than a script. Add one more tool:\n\n``` python\ndef schedule_job(name: str, goal: str, cron: str):\n    from apscheduler.triggers.cron import CronTrigger\n    CronTrigger.from_crontab(cron)                     # raises if invalid\n    count = DB.execute(\"SELECT COUNT(*) FROM jobs\").fetchone()[0]\n    if count >= 20:\n        return {\"error\": \"job limit reached\"}\n    if cron.split()[0].startswith(\"*\"):                # no \"every minute\" jobs\n        return {\"error\": \"minimum interval is hourly\"}\n    DB.execute(\"INSERT OR IGNORE INTO jobs(name, goal, cron, enabled) VALUES(?,?,?,0)\",\n               (name, goal, cron))                     # created disabled\n    DB.commit()\n    return {\"status\": \"pending human approval\"}\n```\n\nGive 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.\n\nThe guardrails are not optional:\n\n`enabled` to 1. Once you trust the pattern, you can auto-approve a narrow safe subset.\nTreat the agent like a new teammate: it can propose, and you approve until it has earned trust.\n\nA few habits separate a toy from something you leave running:\n\n`failed` and `stopped` runs`send_slack` tool so the final report lands where your team already looks.\nAn 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.\n\n*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.*", "url": "https://wpnews.pro/news/how-ai-agents-run-themselves-build-a-scheduled-agentic-system", "canonical_source": "https://dev.to/akumagg/how-ai-agents-run-themselves-build-a-scheduled-agentic-system-ekc", "published_at": "2026-11-23 18:41:29+00:00", "updated_at": "2026-11-23 18:43:18.444770+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "artificial-intelligence"], "entities": ["KeiroLabs", "DataForSEO", "SQLite", "Python"], "also_reported_by": [], "takeaway": "Wrapping an agent's only network access in a handful of explicit tool functions and logging every call to a findings table gives a scheduled agent a hard safety boundary and an auditable run history.", "recommendation": {"advice": "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.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/how-ai-agents-run-themselves-build-a-scheduled-agentic-system", "markdown": "https://wpnews.pro/news/how-ai-agents-run-themselves-build-a-scheduled-agentic-system.md", "text": "https://wpnews.pro/news/how-ai-agents-run-themselves-build-a-scheduled-agentic-system.txt", "jsonld": "https://wpnews.pro/news/how-ai-agents-run-themselves-build-a-scheduled-agentic-system.jsonld"}}