Cron 定時
源码版本v2026.7.20
職責
讓 agent 能「到點自動跑」:定時報告、備份、簡報等不必人在場。cron/ 子系統提供排程器、作業儲存、執行記錄、生命週期守衛、藍圖/建議目錄,以及獨立的 toolsets 隔離(定時任務可停用部分工具,防止無人值守時幹危險事)。網關用 60s 心跳驅動排程器。
關鍵檔案
def run_job:2659— 執行單個作業的核心_run_job_script / _run_job_script_with_claim_heartbeat:2113-2247— 腳本型作業執行 + 租約心跳執行態與中斷:352-445—get_running_job_ids/mark_running_jobs_interrupted/_consume_interrupted_flagtoolsets 解析:143-210—_resolve_cron_disabled_toolsets/_resolve_cron_enabled_toolsets(定時任務的工具隔離)執行緒池:501-547—_get_parallel_pool/_get_sequential_pool_CronStorePaths / _current_cron_store:106-157— 作業儲存路徑鎖與輸出目錄:251-360—_jobs_lock_file/_job_output_dir_normalize_job_record:426-461— 作業記錄標準化執行狀態機:99-156—create_execution/mark_execution_running/finish_executionrecover_interrupted_executions:156-213— 崩潰恢復 +list_executions/latest_executioncheck_gateway_lifecycle:69-112— 防止定時腳本誤操作網關生命週期blueprint_catalog— 作業藍圖目錄suggestion_catalog/suggestions— cron 建議生成_start_cron_ticker:22335— 網關內 60s 心跳驅動排程
資料流
- 網關啟動
_start_cron_ticker:22335,每 60s 觸發排程器。 - 排程器讀作業儲存(
cron/jobs.py:106),按 cron 表達式選出到期作業。 - 每個到期作業:
- 經
check_gateway_lifecycle:112掃描腳本,阻止誤改網關生命週期 - 解析該作業的 toolsets(
cron/scheduler.py:210),通常停用危險工具(見子代理的 auto-deny 同源思路) - 在
create_execution(cron/executions.py:99)記一筆執行 run_job(cron/scheduler.py:2659)實際跑:腳本型走_run_job_script:2113,會話型餵給run_conversation:588
- 經
- 執行中崩潰 → 下次
recover_interrupted_executions(cron/executions.py:156)恢復標記。 - 結果經網關投遞(或 mirror 到指定平台)。
小結
Cron 子系統的重點是「無人值守的安全性」:toolsets 隔離、lifecycle_guard 防誤操作、execution 狀態機做崩潰恢復。排程本身由網關心跳驅動,不需要外部 cron 常駐程式。