如何從零構建可定時執行的 AI 智能體系統
How AI Agents Run Themselves: Build a Scheduled Agentic System
Akuma GG 以 Python 示範從零構建可定時執行的 AI 智能體系統,讓大語言模型調用工具、保存記憶並按排程執行任務。系統以 SQLite 保存任務、執行記錄、工具結果和記憶,並透過 APScheduler 執行 cron 排程;工具包括 KeiroLabs 網頁搜尋與頁面擷取,以及 DataForSEO 關鍵字數據。
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:
- an agent loop that lets an LLM choose tools,
- tools for live web search and page extraction (KeiroLabs) and SEO keyword data (DataForSEO),
- a data layer so the agent remembers and every call is logged,
- a scheduler that runs jobs on a cron schedule,
- and a guardrailed way for the agent to create its own scheduled jobs.
What an agent actually is
Strip away the vocabulary and an agent is four things in a loop:
- A goal written in plain language.
- A model that reads the goal and the history so far.
- Tools the model can call (search, fetch, query, send).
- 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. That is the whole trick. 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.
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.
The data layer comes first
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.
# 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.
The tools
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:
- KeiroLabs for live web search and clean page extraction. The agent uses search to find fresh sources and extraction to read them as text instead of raw HTML.
- An SEO data API (I use DataForSEO) for keyword search volume, so the agent can tell which topics people actually look for.
- Your own APIs later: your database, your CRM, your analytics. Same pattern.
# 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.
The agent loop
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.
# 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_STEPSis your cost ceiling. An agent without one can loop all night. - Tool errors are returned to the model, not raised. The agent can often recover by trying a different query.
-
Every call is written to
findingsbefore the model sees it. If a run fails at step 6, you still have steps 1 to 5.
One run, step by step
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.
The scheduler
Now make it run by itself. APScheduler reads cron strings straight from the jobs table.
# 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.
Letting the agent schedule its own jobs
This is the step that makes it feel like an agent rather than a script. Add one more tool:
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:
- Validate the cron string. Reject anything malformed.
- Set a minimum interval. An agent should never create an every-minute job.
- Cap the total number of jobs.
-
Create jobs disabled. A human flips
enabledto 1. Once you trust the pattern, you can auto-approve a narrow safe subset. -
Cap spend per run and per day. Log token usage and tool calls in
runs.
Treat the agent like a new teammate: it can propose, and you approve until it has earned trust.
Making it dependable
A few habits separate a toy from something you leave running:
- Idempotent writes. Re-running the same job should not corrupt anything.
- Truncate tool output before feeding it back to the model. Pages are huge and tokens are money.
-
Cache expensive calls. Check
findingsfor the same input in the last 24 hours before paying again. -
Alert on
failedandstoppedruns, not just successes. - Never put secrets in prompts or memory. Keep them in environment variables only the tools can read.
- Treat web content as untrusted. A fetched page can contain text that tries to instruct the model. Your tools should only fetch and return data, and anything with side effects (sending email, spending money) should require approval.
Where to go from here
- Add a
send_slacktool so the final report lands where your team already looks. - Add a read-only dashboard over
runsandfindingsso you can see what the agent did. - Split one big job into a planner run that proposes tasks and worker runs that execute them.
- Swap SQLite for Postgres when more than one process needs the same data.
The takeaway
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.
來源:DEV Community · dev.to

