编程-学习-思考

s14:Cron Scheduler——定时触发,不需要人推

s14:Cron Scheduler——定时触发,不需要人推

“定时触发,不需要人推。” ——按时间自动触发任务,调度与执行解耦。

问题

闹钟不需要你盯着它才会响。你设好 7:00,到点它自己响。你在睡觉、在洗澡、在做饭,它都照响不误。

s13 让 Agent 能后台执行慢操作,但所有操作仍然是你手动触发的。你说一句,Agent 动一下。”每天早上 9 点跑测试”、”每 30 分钟检查 CI 状态”——这些周期性任务不该需要人每次来推。

解决方案

四层模型:

  1. Scheduler:daemon 线程,每秒轮询,判断时间到了没有
  2. Queue:cron_queue,调度线程写入已触发任务
  3. Queue Processor:发现队列非空且 Agent 空闲,启动 agent_loop
  4. Consumer:agent_loop 从队列消费,注入到 messages

工作原理

CronJob: 数据结构

@dataclass
class CronJob:
    id: str
    cron: str        # "0 9 * * *" (五段式 cron 表达式)
    prompt: str      # 触发时注入给 Agent 的消息
    recurring: bool  # True=周期性,False=一次性
    durable: bool    # True=写磁盘,跨会话保留

Cron 表达式,五段式,Unix 用了 50 年:

分钟  小时  日  月  星期
  *    *   *   *   *      每分钟
  0    9   *   *   *      每天早上 9:00
 */5    *   *   *   *      每 5 分钟
  0    9   *   *  1-5     工作日早上 9:00

独立调度线程:每秒轮询

调度器跑在独立的 daemon 线程里,不依赖 agent_loop 是否在执行:

def cron_scheduler_loop():
    while True:
        time.sleep(1)
        now = datetime.now()
        minute_marker = now.strftime("%Y-%m-%d %H:%M")
        with cron_lock:
            for job in list(scheduled_jobs.values()):
                try:
                    if cron_matches(job.cron, now):
                        if _last_fired.get(job.id) != minute_marker:
                            cron_queue.append(job)
                            _last_fired[job.id] = minute_marker
                        if not job.recurring:
                            scheduled_jobs.pop(job.id, None)
                            if job.durable:
                                save_durable_jobs()
                except Exception as e:
                    print(f"[cron error] {job.id}: {e}")

关键设计:

  • 独立于 agent_loop:即使 agent_loop 没在跑,调度器也在后台检查时间
  • date-aware minute_marker:用 "YYYY-MM-DD HH:MM" 防止同一分钟重复触发
  • 单 job try/except:一个坏 job 不会拖垮整个调度线程
  • 一次性任务:触发后自动从 scheduled_jobs 中删除

Queue Processor:空闲自动交付

def queue_processor_loop():
    while True:
        time.sleep(0.2)
        if not has_cron_queue(): continue
        if not agent_lock.acquire(blocking=False): continue
        try:
            if has_cron_queue():
                run_agent_turn_locked()
        finally:
            agent_lock.release()

agent_loop 只从 cron_queue 里拿已触发的任务,注入到 messages:

fired = consume_cron_queue()
for job in fired:
    messages.append({"role": "user", "content": f"[Scheduled] {job.prompt}"})

Durable vs Session-only

  • Durable:任务定义写进 .scheduled_tasks.json。Agent 重启后加载文件恢复任务。
  • Session-only:只在内存里。Agent 关闭就没了。

重要:cron 调度器必须在 Agent 进程内跑。进程关闭,调度也停。Durable 只意味着任务定义跨重启保留,下次 Agent 启动时调度器才会触发。

完整流程

1. 启动时:
   load_durable_jobs() → 从 .scheduled_tasks.json 恢复持久化任务
   Thread(cron_scheduler_loop).start() → 调度线程开始轮询
   Thread(queue_processor_loop).start() → 队列处理器等待交付

2. 注册任务:
   schedule_cron(cron="*/2 * * * *", prompt="run date", durable=True)
   → CronJob 写入 scheduled_jobs + .scheduled_tasks.json

3. 每 2 分钟:
   调度线程检查 → cron_matches 返回 True → cron_queue.append(job)
   → queue processor 发现 Agent 空闲 → agent_loop consume
   → 注入 "[Scheduled] run date"
   → LLM 收到消息,执行 date 命令

对比上一章

组件 s13 s14
触发方式 用户手动触发 调度线程自动入队
新存储 — .scheduled_tasks.json (durable) + 内存 (session-only)
线程 后台执行线程 + 调度线程 + queue processor 线程
队列 background_results + cron_queue

试一下

python s14_cron_scheduler/code.py

试试:

  1. Schedule a task to print the current date every 2 minutes
  2. Create a one-shot reminder in 1 minute to check the build status
  3. 不输入新 prompt,观察是否自动出现 [queue processor] 并执行

观察:调度线程是否在独立运行?cron 任务是否在正确的时间点触发?

接下来

一个 Agent 能做很多事了。但有些任务太大了,不是一个 Agent 能搞定的。”重构整个后端”需要一个团队。

s15 Agent Teams → 一个 Agent 不够,组队吧。持久队友 + 异步收件箱。