Hermes Agent 定时任务(Cron)实战:在 3060 12G 显卡上打造 7×24 无人值守自动化流水线


title: Hermes Agent 定时任务(Cron)实战:在 3060 12G 显卡上打造 7×24 无人值守自动化流水线

Hermes Agent 定时任务(Cron)实战:在 3060 12G 显卡上打造 7×24 无人值守自动化流水线

引言

当你已经在 3060 12G 显卡上成功部署了 Hermes Agent,下一个核心问题就是——如何让智能体自主运行,而非每次手动触发?

Hermes Agent 内置了强大的 Cron 定时任务系统,允许你像配置 Linux crontab 一样,定义智能体在特定时间执行特定任务。结合本地 3060 显卡的推理能力,你可以实现一个真正的 7×24 无人值守自动化流水线:定时抓取数据、定时生成报告、定时发布内容、定时清理日志……所有操作都在本地完成,无需依赖任何外部云服务。

本文将深入 Hermes Agent 的 Cron 调度系统,从基础配置到高级实战,带你一步步打造属于自己的自动化智能体。


一、Hermes Agent Cron 系统核心概念

1.1 什么是 Hermes Cron?

Hermes Agent 的 Cron 系统是一个基于技能(Skill)的定时任务调度器。每个 Cron 任务本质上是一次对某个 Skill 的调用,系统会在设定的时间点自动运行该 Skill,并将输出记录到日志中。

核心架构如下:

┌─────────────────┐
│   Cron Scheduler │  ← 每分钟检查一次
│   (Go 实现)      │
└────────┬────────┘
         │ 触发
         ▼
┌─────────────────┐
│   Skill Engine   │  ← 加载特定 Skill
│   (Python)       │
└────────┬────────┘
         │ 执行
         ▼
┌─────────────────┐
│   Hermes Agent   │  ← 调用 LLM + Tools
│   (核心引擎)      │
└────────┬────────┘
         │ 输出
         ▼
┌─────────────────┐
│   日志 + 通知     │  ← 错误告警 / 成功回调
└─────────────────┘

1.2 Cron 配置文件结构

Cron 配置文件是 YAML 格式,存放在 Hermes 配置目录下:

# ~/.hermes/profiles/default/cron/tasks.yaml

tasks:
  - name: "daily_blog_publisher"
    schedule: "0 8 * * *"           # 每天早上 8 点
    skill: "blog-publisher"
    input: "生成一篇关于 AI 技术的文章并发布"
    notify_on_error: true

  - name: "weekly_report"
    schedule: "0 9 * * 1"           # 每周一早上 9 点
    skill: "report-generator"
    input: "汇总上周工作数据生成周报"
    notify_on_error: true
    max_retries: 3

  - name: "log_cleanup"
    schedule: "0 3 * * 0"           # 每周日凌晨 3 点
    skill: "system-maintenance"
    input: "清理超过 7 天的日志文件"
    notify_on_error: false

二、实战步骤:构建 3060 本地自动化流水线

2.1 创建自定义 Skill —— 自动化博客发布

首先创建一个专门用于自动撰写和发布技术博客的 Skill:

# 创建 skill 目录
mkdir -p ~/.hermes/skills/auto-blogger

# 创建 skill 定义文件
cat > ~/.hermes/skills/auto-blogger/skill.json << 'EOF'
{
  "name": "auto-blogger",
  "version": "1.0.0",
  "description": "自动撰写并发布技术博客到 WordPress",
  "author": "hermes-user",
  "inputs": [
    {
      "name": "topic",
      "type": "string",
      "description": "博客主题或关键词",
      "required": true
    },
    {
      "name": "style",
      "type": "string",
      "description": "写作风格(tech/deep-dive/tutorial)",
      "default": "tutorial"
    }
  ],
  "tools": ["write_file", "terminal", "read_file"],
  "hooks": {
    "on_success": "notify_success",
    "on_error": "notify_error"
  }
}
EOF

2.2 编写 Skill 执行脚本

Skill 的核心是 run.py,它定义了智能体在收到定时触发时的具体行为:

#!/usr/bin/env python3
"""
auto-blogger Skill — 自动撰写并发布技术博客
"""
import json
import sys
import subprocess
import os
from datetime import datetime

def main():
    # 从环境变量或 stdin 获取输入
    input_data = json.loads(sys.stdin.read())
    topic = input_data.get("topic", "技术分享")
    style = input_data.get("style", "tutorial")

    # 生成博客内容
    article_path = f"/tmp/auto_blog_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"

    # 调用 Hermes Agent API 生成文章
    prompt = f"""请撰写一篇关于「{topic}」的技术博客,风格为 {style}。
要求:
- 包含引言、核心概念、实战步骤、常见问题、总结五个部分
- 至少包含 3 个代码块
- 语言:中文
- 字数:1500-2500 字"""

    result = subprocess.run(
        ["hermes", "run", "--prompt", prompt],
        capture_output=True, text=True, timeout=300
    )

    if result.returncode != 0:
        print(json.dumps({"status": "error", "message": result.stderr}))
        sys.exit(1)

    # 保存文章到临时文件
    with open(article_path, "w") as f:
        f.write(result.stdout)

    # 调用发布脚本
    publish_script = os.path.expanduser(
        "~/.hermes/skills/web-development/wordpress-install/scripts/direct-publish.sh"
    )
    pub_result = subprocess.run(
        ["bash", publish_script, article_path],
        capture_output=True, text=True, timeout=60
    )

    output = {
        "status": "success" if pub_result.returncode == 0 else "failed",
        "article": article_path,
        "publish_log": pub_result.stdout,
        "timestamp": datetime.now().isoformat()
    }
    print(json.dumps(output))

if __name__ == "__main__":
    main()

2.3 配置 Cron 定时任务

将 Skill 注册到 Cron 调度器中:

# ~/.hermes/profiles/default/cron/tasks.yaml

tasks:
  - name: "morning_blog"
    schedule: "30 7 * * *"           # 每天 7:30 执行
    skill: "auto-blogger"
    input:
      topic: "Hermes Agent 实战技巧"
      style: "tutorial"
    notify_on_error: true
    max_retries: 2
    timeout: 600                     # 最长执行 10 分钟

  - name: "afternoon_data_pipeline"
    schedule: "0 14 * * 1-5"         # 工作日 14:00 执行
    skill: "data-pipeline"
    input: "爬取今日技术资讯并生成摘要"
    timeout: 900

  - name: "night_system_check"
    schedule: "0 2 * * *"            # 每天凌晨 2 点
    skill: "system-maintenance"
    input: "检查磁盘使用率、清理临时文件、重启异常服务"
    notify_on_error: true

2.4 Cron 表达式速查

Hermes Agent 使用标准的 5 段式 Cron 表达式:

表达式 含义
*/5 * * * * 每 5 分钟执行一次
0 * * * * 每小时整点执行
0 9 * * 1-5 工作日每天早上 9 点
0 0 1 * * 每月 1 号凌晨执行
30 22 * * 6 每周六晚上 10:30
0 */3 * * * 每 3 小时执行一次

2.5 启动和验证 Cron 服务

# 1. 重新加载 Cron 配置
hermes cron reload

# 2. 查看所有已注册的定时任务
hermes cron list

# 输出示例:
# ┌──────┬────────────────────┬──────────┬─────────────────────┬────────┐
# │ ID   │ Name               │ Schedule │ Next Run            │ Status │
# ├──────┼────────────────────┼──────────┼─────────────────────┼────────┤
# │ 1    │ morning_blog       │ 30 7 * * │ 2026-06-09 07:30:00 │ active │
# │ 2    │ afternoon_pipeline │ 0 14 * * │ 2026-06-09 14:00:00 │ active │
# │ 3    │ night_system_check │ 0 2 * *  │ 2026-06-09 02:00:00 │ active │
# └──────┴────────────────────┴──────────┴─────────────────────┴────────┘

# 3. 查看执行历史
hermes cron history --limit 10

# 4. 手动触发一次测试(不等待定时)
hermes cron run morning_blog --now

# 5. 查看实时日志
tail -f ~/.hermes/profiles/default/logs/cron.log

三、高级技巧与最佳实践

3.1 多任务依赖与条件执行

某些场景下,任务 B 需要等待任务 A 完成后才能执行。可以通过 Shell 脚本实现简单的依赖链:

#!/bin/bash
# ~/.hermes/cron/scripts/dependency_runner.sh

# 等待前置任务完成
TASK_A_ID=$(hermes cron run data-collector --now --json | jq -r '.task_id')

# 轮询状态直到完成
while true; do
    STATUS=$(hermes cron status "$TASK_A_ID" --json | jq -r '.status')
    if [ "$STATUS" == "success" ]; then
        echo "前置任务完成,启动后续流程"
        hermes cron run report-generator --now
        break
    elif [ "$STATUS" == "failed" ]; then
        echo "前置任务失败,发送告警"
        hermes cron run alert-notifier --input "数据采集任务失败"
        exit 1
    fi
    sleep 30
done

3.2 错误重试与告警

在生产环境中,网络抖动、API 限流等都可能导致任务失败。配置合理的重试策略至关重要:

# 重试配置示例
tasks:
  - name: "critical_data_sync"
    schedule: "0 */6 * * *"
    skill: "data-sync"
    input: "同步生产数据库到分析实例"
    max_retries: 5                    # 最多重试 5 次
    retry_delay: 120                  # 每次重试间隔 120 秒
    retry_backoff: 2.0                # 指数退避(120s → 240s → 480s ...)
    notify_on_error: true
    notify_on_retry: true             # 每次重试也通知
    notify_endpoint: "https://api.telegram.org/bot<TOKEN>/sendMessage"
    timeout: 1800

3.3 在 3060 上优化 Cron 任务资源

3060 12G 显存适合同时运行 1~2 个推理任务。配置资源限制避免 OOM:

# 全局资源限制
global:
  max_concurrent_tasks: 2            # 最多同时运行 2 个任务
  task_timeout_default: 300
  memory_limit_per_task: "4G"        # 每个任务限 4GB 内存
  gpu_memory_limit: "6G"             # 每个任务限 6GB 显存

tasks:
  - name: "heavy_inference"
    schedule: "0 3 * * *"
    skill: "video-summarizer"
    input: "处理昨日监控视频"
    gpu_memory_limit: "10G"          # 独占大部分显存
    timeout: 3600
    # 这个任务在凌晨执行,可以独占资源

3.4 日志轮转与监控

#!/usr/bin/env python3
"""cron_log_monitor.py — 监控 Cron 任务健康状态"""
import json
import subprocess
import time
from datetime import datetime, timedelta

def check_cron_health():
    """检查过去 24 小时内的任务执行情况"""
    result = subprocess.run(
        ["hermes", "cron", "history", "--since", "24h", "--json"],
        capture_output=True, text=True
    )
    tasks = json.loads(result.stdout)

    failures = [t for t in tasks if t["status"] == "failed"]
    total = len(tasks)

    report = {
        "timestamp": datetime.now().isoformat(),
        "total_tasks_24h": total,
        "failed_tasks": len(failures),
        "success_rate": f"{(total - len(failures)) / total * 100:.1f}%",
        "failures_detail": [
            {"name": t["name"], "time": t["executed_at"], "error": t["error"]}
            for t in failures[:5]
        ]
    }

    if failures:
        print(f"[ALERT] {report['failed_tasks']}/{report['total_tasks_24h']} 任务失败")
        print(json.dumps(report, indent=2, ensure_ascii=False))

    return report

if __name__ == "__main__":
    # 每分钟检查一次(配合 systemd timer 或 crontab)
    check_cron_health()

四、常见问题

Q1: Cron 任务没有按时触发怎么办?

排查步骤:

# 1. 检查 Cron 守护进程是否在运行
hermes cron status

# 2. 检查日志有无错误
tail -50 ~/.hermes/profiles/default/logs/cron.log

# 3. 检查时间是否正确
date && timedatectl

# 4. 手动触发测试
hermes cron run <task_name> --now

Q2: 如何在 Cron 任务中使用环境变量?

~/.hermes/profiles/default/env.yaml 中定义全局环境变量:

# env.yaml
environment:
  WORDPRESS_URL: "https://www.stellardata.top"
  WORDPRESS_USER: "admin"
  PYTHONPATH: "/home/wwwroot/scripts"
  OPENAI_API_KEY: "${OPENAI_API_KEY}"   # 引用系统环境变量
  TZ: "Asia/Shanghai"

Q3: 任务超时了如何处理?

调整任务的 timeout 参数或拆分长时间任务:

# 查看超时任务详情
hermes cron inspect <task_id>

# 增加超时时间(编辑 tasks.yaml 后 reload)
hermes cron reload

# 或将大任务拆分为多个小任务链式执行
# task1: 数据采集(30分钟)
# task2: 数据清洗(10分钟)
# task3: 数据发布(5分钟)

Q4: 3060 12G 能跑多少个并发 Cron 任务?

实测建议:

模型规模 显存占用 建议并发数
7B 模型 (Q4) ~6GB 2 个并发
13B 模型 (Q4) ~8GB 1 个
调用 API(非本地推理) ~0.5GB 无限制

建议在 tasks.yaml 中设置 max_concurrent_tasks: 2 确保稳定性。


五、总结

通过 Hermes Agent 的 Cron 定时任务系统,你可以在 3060 12G 显卡的本地机器上构建一个真正自主运行、无需人工干预的智能体流水线。本文从 Cron 配置基础出发,逐步深入到 Skill 开发、多任务编排、错误重试、资源限制和健康监控,覆盖了生产环境部署的全链路知识。

关键要点回顾:

  1. Cron + Skill 是最佳搭档 — Skill 定义”做什么”,Cron 定义”什么时候做”
  2. 善用重试和资源限制 — 让 3060 12G 的硬件资源得到最大化利用
  3. 日志和监控不可忽视 — 无人值守不代表完全不管,健康检查是最后一道防线
  4. 从简单开始,逐步扩展 — 先配一个每日博客发布任务,再逐步添加其他流水线

下一步可以尝试:将 Hermes Agent 与微信/Telegram Bot 集成,通过消息指令触发特定 Cron 任务,实现”随时随地远程指挥你的本地智能体”。整个系统完全私有化部署,数据不出本机——这才是真正属于你自己的 AI 自动化平台。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片快捷回复

    暂无评论内容