跳到主要内容

用 Cron 自动化任何事情

daily briefing bot tutorial 介绍了基础能力。本指南会更进一步,给出五种可以直接迁移到你自己工作流里的真实自动化模式。

完整功能参考请见 Scheduled Tasks (Cron)

核心概念

Cron 任务总是在一个全新的 agent 会话中运行,不会记住你当前聊天里的上下文。因此 prompt 必须 完全自包含,把 agent 需要知道的信息全部写进去。


模式 1:网站变更监控

监控某个 URL 是否变化,并且只在真的发生变化时通知你。

这里的关键武器是 script 参数。每次执行前都会先运行一个 Python 脚本,它的 stdout 会作为上下文传给 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")

# Fetch current content
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()

# Load previous state
prev_hash = None
if os.path.exists(STATE_FILE):
with open(STATE_FILE) as f:
prev_hash = json.load(f).get("hash")

# Save current state
with open(STATE_FILE, "w") as f:
json.dump({"hash": current_hash, "url": URL}, f)

# Output for the 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:周报生成

把多个来源的信息汇总成格式化摘要。这个任务每周运行一次,并投递到你的 home channel。

/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 仓库观察器

监控一个仓库中的新 issue、PR 或 release。

/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
自包含 Prompt

注意这个 prompt 把要执行的 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)

# Fetch current data (example: crypto prices)
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())

# Append to history file
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")

# Load recent history for analysis
lines = open(history_file).readlines()
recent = [json.loads(l) for l in lines[-24:]] # Last 24 data points

# Output for the 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:多技能工作流

把多个技能串联在一起执行复杂的定时任务。技能会在 prompt 执行前按顺序加载。

# Use the arxiv skill to find papers, then the obsidian skill to save notes
/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 如何写入笔记),最后由 prompt 把两者串起来。


管理你的任务

# List all active jobs
/cron list

# Trigger a job immediately (for testing)
/cron run <job_id>

# Pause a job without deleting it
/cron pause <job_id>

# Edit a running job's schedule or prompt
/cron edit <job_id> --schedule "every 4h"
/cron edit <job_id> --prompt "Updated task description"

# Add or remove skills from an existing job
/cron edit <job_id> --skill arxiv --skill obsidian
/cron edit <job_id> --clear-skills

# Remove a job permanently
/cron remove <job_id>

投递目标

--deliver 参数决定结果发往哪里:

TargetExampleUse case
origin--deliver origin发回创建该任务的原聊天(默认)
local--deliver local只保存到本地文件
telegram--deliver telegram发到你的 Telegram home channel
discord--deliver discord发到你的 Discord home channel
slack--deliver slack发到你的 Slack home channel
Specific chat--deliver telegram:-1001234567890指定 Telegram 群组
Threaded--deliver telegram:-1001234567890:17585指定 Telegram 话题线程

提示

让 prompt 自包含。 Cron 任务中的 agent 不会记住你的对话。URL、仓库名、格式要求和投递说明都要直接写进 prompt。

多用 [SILENT] 对于监控型任务,应始终加上“如果没有变化就返回 [SILENT]”之类的要求,避免无意义通知。

用脚本做数据采集。 script 参数适合让 Python 脚本处理枯燥部分,如 HTTP 请求、文件 IO 和状态追踪。agent 只看脚本 stdout 并做推理,这通常比让 agent 自己去抓取更便宜也更稳定。

/cron run 测试。 不要等调度器触发后才发现问题,先用 /cron run <job_id> 立即执行一次,确认输出是否符合预期。

调度表达式格式。 支持相对延迟(30m)、固定间隔(every 2h)、标准 cron 表达式(0 9 * * *)和 ISO 时间戳(2025-06-15T09:00:00)。像 daily at 9am 这样的自然语言并不支持,请改用 0 9 * * *


完整的 cron 参考,包括全部参数、边界情况和内部机制,请见 Scheduled Tasks (Cron)