Skip to content

使用 Cron 自动化任何事情

hermes agent 使用 Cron 自动化任何事情

每日简报机器人教程涵盖了基础内容。本指南会进一步深入 —— 提供五种真实场景中的自动化模式,你可以根据自己的工作流进行调整。

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

监控一个 URL 的变化,并且只有在内容不同时才收到通知。

这里的 script 参数是秘密武器。每次执行前会先运行一个 Python 脚本,它的 stdout 会成为 agent 的上下文。脚本负责机械性工作(获取、diff);agent 负责推理(这个变化是否重要?)。

创建监控脚本:

Terminal window
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 job:

/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

将多个来源的信息汇总成格式化摘要。它每周运行一次,并投递到你的 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:

Terminal window
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。

监控一个仓库是否有新的 issues、PRs 或 releases。

/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

按固定间隔抓取数据,保存到文件,并随时间检测趋势。这个模式将脚本(用于收集)与 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 添加推理层。

将 skills 串联起来,用于复杂的定时任务。Skills 会在 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"
)

Skills 会按顺序加载 —— 先加载 arxiv(教 agent 如何搜索论文),再加载 obsidian(教它如何写笔记)。prompt 会把它们串联起来。

Terminal window
# 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 flag 控制结果发送到哪里:

目标示例使用场景
origin--deliver origin创建该 job 的同一个聊天(默认)
local--deliver local仅保存到本地文件
telegram--deliver telegram你的 Telegram home channel
discord--deliver discord你的 Discord home channel
slack--deliver slack你的 Slack home channel
指定聊天--deliver telegram:-1001234567890指定的 Telegram 群组
线程化--deliver telegram:-1001234567890:17585指定的 Telegram topic thread

让 prompts 自包含。cron job 中的 agent 不记得你的对话。请直接在 prompt 中包含 URLs、repo names、格式偏好和投递说明。

大量使用 [SILENT]。对于监控 jobs,始终包含类似“如果没有变化,回复 [SILENT]”这样的指令。这可以防止通知噪音。

使用 scripts 进行数据收集。script 参数可以让 Python 脚本处理无聊的部分(HTTP requests、file I/O、state tracking)。agent 只会看到脚本的 stdout,并对其应用推理。相比让 agent 自己抓取内容,这种方式更便宜,也更可靠。

使用 /cron run 测试。在等待 schedule 触发之前,使用 /cron run <job_id> 立即执行,并确认输出看起来正确。

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

完整的 cron 参考 —— 所有参数、边界情况和内部机制 —— 请参见 Scheduled Tasks(Cron)。

-
0:000:00