跳到主要內容

使用 Cron 自動化任何任務

每日簡報機器人教程 涵蓋了基礎知識。本指南更進一步——介紹五個可應用於您自身工作流的真實世界自動化模式。

如需完整功能參考,請參閱 計劃任務(Cron)

關鍵概念

Cron 任務在全新的 Agent 會話中運行,不會保留您當前聊天的記憶。提示必須是完全自包含的——包含 Agent 所需的一切信息。


模式 1:網站變更監控器

監控指定 URL 的變更,並僅在內容發生變化時收到通知。

script 參數是此模式的關鍵。每次執行前都會運行一段 Python 腳本,其標準輸出將作為 Agent 的上下文。腳本負責機械性工作(獲取網頁內容、對比差異);Agent 則負責推理判斷(此變更是否值得關注?)。

創建監控腳本:

mkdir -p ~/.hermes/scripts
~/.hermes/scripts/watch-site.py
import hashlib, json, os, urllib.request

URL = "https://example.com/pricing"
STATE_FILE = os.path.expanduser("~/.hermes/scripts/.watch-site-state.json")

# 獲取當前內容
req = urllib.request.Request(URL, headers={"User-Agent": "Hermes-Monitor/1.0"})
content = urllib.request.urlopen(req, timeout=30).read().decode()
current_hash = hashlib.sha256(content.encode()).hexdigest()

# 加載之前的狀態
prev_hash = None
if os.path.exists(STATE_FILE):
with open(STATE_FILE) as f:
prev_hash = json.load(f).get("hash")

# 保存當前狀態
with open(STATE_FILE, "w") as f:
json.dump({"hash": current_hash, "url": URL}, f)

# 輸出給 Agent
if prev_hash and prev_hash != current_hash:
print(f"CHANGE DETECTED on {URL}")
print(f"Previous hash: {prev_hash}")
print(f"Current hash: {current_hash}")
print(f"\nCurrent content (first 2000 chars):\n{content[:2000]}")
else:
print("NO_CHANGE")

設置 Cron 任務:

/cron add "every 1h" "If the script output says CHANGE DETECTED, summarize what changed on the page and why it might matter. If it says NO_CHANGE, respond with just [SILENT]." --script ~/.hermes/scripts/watch-site.py --name "Pricing monitor" --deliver telegram
[SILENT] 技巧

當 Agent 的最終響應包含 [SILENT] 時,將抑制通知發送。這意味著只有真正發生變更時才會收到提醒——在無變化時段不會產生通知噪音。


模式 2:每週報告

從多個信息源彙總數據,生成格式化的摘要報告。該任務每週運行一次,併發送至您的主頻道。

/cron add "0 9 * * 1" "Generate a weekly report covering:

1. Search the web for the top 5 AI news stories from the past week
2. Search GitHub for trending repositories in the 'machine-learning' topic
3. Check Hacker News for the most discussed AI/ML posts

Format as a clean summary with sections for each source. Include links.
Keep it under 500 words — highlight only what matters." --name "Weekly AI digest" --deliver telegram

通過 CLI 執行:

hermes cron create "0 9 * * 1" \
"Generate a weekly report covering the top AI news, trending ML GitHub repos, and most-discussed HN posts. Format with sections, include links, keep under 500 words." \
--name "Weekly AI digest" \
--deliver telegram

0 9 * * 1 是標準的 Cron 表達式:每週一上午 9:00。


模式 3:GitHub 倉庫監視器

監視倉庫中是否有新問題、拉取請求或發佈版本。

/cron add "every 6h" "Check the GitHub repository NousResearch/hermes-agent for:
- New issues opened in the last 6 hours
- New PRs opened or merged in the last 6 hours
- Any new releases

Use the terminal to run gh commands:
gh issue list --repo NousResearch/hermes-agent --state open --json number,title,author,createdAt --limit 10
gh pr list --repo NousResearch/hermes-agent --state all --json number,title,author,createdAt,mergedAt --limit 10

Filter to only items from the last 6 hours. If nothing new, respond with [SILENT].
Otherwise, provide a concise summary of the activity." --name "Repo watcher" --deliver discord
完全自包含的提示

請注意提示中如何明確包含 gh 命令。Cron Agent 沒有記憶前次運行或您的偏好的能力——必須完整寫出所有指令。


模式 4:數據收集流水線

定期抓取數據,保存到文件,並隨時間檢測趨勢。該模式結合腳本(用於收集)與 Agent(用於分析)。

~/.hermes/scripts/collect-prices.py
import json, os, urllib.request
from datetime import datetime

DATA_DIR = os.path.expanduser("~/.hermes/data/prices")
os.makedirs(DATA_DIR, exist_ok=True)

# 獲取當前數據(例如:加密貨幣價格)
url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd"
data = json.loads(urllib.request.urlopen(url, timeout=30).read())

# 追加到歷史文件
entry = {"timestamp": datetime.now().isoformat(), "prices": data}
history_file = os.path.join(DATA_DIR, "history.jsonl")
with open(history_file, "a") as f:
f.write(json.dumps(entry) + "\n")

# 加載最近的歷史記錄進行分析
lines = open(history_file).readlines()
recent = [json.loads(l) for l in lines[-24:]] # 最後 24 個數據點

# 輸出給 Agent
print(f"Current: BTC=${data['bitcoin']['usd']}, ETH=${data['ethereum']['usd']}")
print(f"Data points collected: {len(lines)} total, showing last {len(recent)}")
print(f"\nRecent history:")
for r in recent[-6:]:
print(f" {r['timestamp']}: BTC=${r['prices']['bitcoin']['usd']}, ETH=${r['prices']['ethereum']['usd']}")
/cron add "every 1h" "Analyze the price data from the script output. Report:
1. Current prices
2. Trend direction over the last 6 data points (up/down/flat)
3. Any notable movements (>5% change)

If prices are flat and nothing notable, respond with [SILENT].
If there's a significant move, explain what happened." \
--script ~/.hermes/scripts/collect-prices.py \
--name "Price tracker" \
--deliver telegram

腳本負責機械性數據收集;Agent 則添加推理分析層。


模式 5:多技能工作流

將多個技能串聯起來,完成複雜的計劃任務。技能在提示執行前按順序加載。

# 使用arxiv skill查找論文,然後使用黑曜石skill保存筆記
/cron add "0 8 * * *" "Search arXiv for the 3 most interesting papers on 'language model reasoning' from the past day. For each paper, create an Obsidian note with the title, authors, abstract summary, and key contribution." \
--skill arxiv \
--skill obsidian \
--name "Paper digest"

通過工具直接執行:

cronjob(
action="create",
skills=["arxiv", "obsidian"],
prompt="Search arXiv for papers on 'language model reasoning' from the past day. Save the top 3 as Obsidian notes.",
schedule="0 8 * * *",
name="Paper digest",
deliver="local"
)

技能按順序加載——首先是 arxiv(教會 Agent 如何搜索論文),然後是 obsidian(教會 Agent 如何撰寫筆記)。提示將它們串聯起來。


管理您的任務

# 列出所有活動作業
/cron list

# 立即觸發作業(用於測試)
/cron run <job_id>

# 暫停作業而不刪除它
/cron pause <job_id>

# 編輯正在運行的作業的計劃或 prompt
/cron edit <job_id> --schedule "every 4h"
/cron edit <job_id> --prompt "Updated task description"

# 在現有作業中添加或刪除 skills
/cron edit <job_id> --skill arxiv --skill obsidian
/cron edit <job_id> --clear-skills

# 永久刪除職位
/cron remove <job_id>

交付目標

--deliver 標誌控制結果的發送位置:

目標示例使用場景
origin--deliver origin創建任務的原始聊天(默認)
local--deliver local僅保存到本地文件
telegram--deliver telegram您的 Telegram 主頻道
discord--deliver discord您的 Discord 主頻道
slack--deliver slack您的 Slack 主頻道
特定聊天--deliver telegram:-1001234567890指定的 Telegram 群組
線程--deliver telegram:-1001234567890:17585指定的 Telegram 主題線程

技巧

使提示完全自包含。 Cron 任務中的 Agent 沒有記憶您對話的能力。請在提示中直接包含 URL、倉庫名稱、格式偏好和交付指令。

廣泛使用 [SILENT] 對於監控類任務,始終包含類似“若無變化,請回復 [SILENT]”的指令。這可防止通知噪音。

使用腳本進行數據收集。 script 參數允許 Python 腳本處理繁瑣部分(HTTP 請求、文件 I/O、狀態追蹤)。Agent 僅看到腳本的標準輸出,並基於此進行推理。相比讓 Agent 自行執行獲取操作,這種方式更經濟且更可靠。

使用 /cron run 測試。 在等待計劃觸發前,可使用 /cron run <job_id> 立即執行任務,驗證輸出是否正確。

調度表達式。 人類可讀格式如 every 2h30mdaily at 9am 均支持,同時兼容標準 Cron 表達式如 0 9 * * *


如需完整的 Cron 參考——包含所有參數、邊緣情況和內部機制——請參閱 計劃任務(Cron)