⏰ OpenClaw 定时任务配置详解
"凌晨3点47分,全世界都在睡觉,只有我的 Agent 还在跑。它不会累,不会抱怨,只是安静地完成每一个任务。"
为什么需要定时任务?
想象一下:你每天要手动检查网站死链、生成数据报告、发布内容到社区... 这些事情重复、枯燥,还容易忘。定时任务就是让 Agent 替你完成这些"苦力活",真正实现"睡后收入"。
OpenClaw 的定时任务系统基于 cron 表达式,支持从简单的时间触发到复杂的工作流编排。
核心功能介绍
- Cron 调度 - 使用标准 cron 表达式定义执行时间
- 任务队列 - 支持并发控制和任务优先级
- 重试机制 - 失败自动重试,支持指数退避
- 执行日志 - 完整记录每次执行状态和输出
- Webhook 通知 - 任务完成/失败时发送通知
快速开始
添加第一个定时任务
# 基本语法
openclaw cron add \
--name "daily-report" \
--schedule "0 9 * * *" \
--agent seo-reporter \
--task "生成每日SEO报告"
# 响应
✓ 任务已创建: daily-report
ID: cron_a1b2c3d4
下次执行: 2026-04-14 09:00:00
Cron 表达式速查
| 表达式 | 含义 | 说明 |
|---|---|---|
0 * * * * |
每小时执行 | 整点触发 |
0 0 * * * |
每天午夜 | 0点0分 |
0 9 * * 1-5 |
工作日早9点 | 周一到周五 |
*/30 * * * * |
每30分钟 | 间隔执行 |
0 0 * * 0 |
每周日午夜 | 周报生成 |
高级配置
任务配置文件
# cron.config.yaml
jobs:
# SEO 日报生成
- name: seo-daily-report
schedule: "0 8 * * *"
agent: seo-agent
task:
type: generate-report
template: daily-seo
output: /reports/seo/{{date}}.html
retry:
maxAttempts: 3
backoff: exponential
delay: 60s
notify:
onSuccess: webhook://discord.com/api/webhooks/xxx
onFailure: email://admin@example.com
# 竞品监控(每6小时)
- name: competitor-watch
schedule: "0 */6 * * *"
agent: research-agent
task:
type: monitor-competitors
targets:
- futuretools.io
- theresanaiforthat.com
output: /reports/competitor/{{date}}.md
concurrency:
max: 2 # 同时最多2个竞品分析
# 社区内容发布
- name: social-post
schedule: "0 10,14,18 * * *"
agent: content-agent
task:
type: publish-social
platforms:
- discord
- twitter
contentSource: /content/scheduled/
condition:
# 只在有内容时才执行
check: "has-files /content/scheduled/"
程序化创建任务
const { CronManager } = require('openclaw/cron');
class TaskScheduler {
constructor() {
this.cron = new CronManager();
}
async setupDailyTasks() {
// 早间新闻聚合
await this.cron.createJob({
name: 'morning-news',
schedule: '0 7 * * *',
agent: 'news-aggregator',
task: {
type: 'aggregate-rss',
sources: [
'https://openai.com/blog/rss.xml',
'https://www.anthropic.com/rss.xml'
],
output: '/news/daily-{{date}}.html',
format: 'newsletter'
},
options: {
timezone: 'Asia/Shanghai',
retry: { attempts: 3, delay: 300 }
}
});
// 网站死链检查
await this.cron.createJob({
name: 'link-checker',
schedule: '0 2 * * *', // 凌晨2点
agent: 'seo-agent',
task: {
type: 'check-dead-links',
site: 'https://miaoquai.com',
notifyOnFailure: true
}
});
console.log('定时任务配置完成');
}
// 动态添加一次性任务
async scheduleOneTime(task) {
const runAt = new Date(Date.now() + task.delayMs);
return await this.cron.createJob({
name: `one-time-${Date.now()}`,
schedule: `at ${runAt.toISOString()}`,
agent: task.agent,
task: task.payload,
options: {
deleteAfterRun: true // 执行后自动删除
}
});
}
}
// 使用
const scheduler = new TaskScheduler();
await scheduler.setupDailyTasks();
最佳实践
✅ 任务设计原则
- 错峰执行 - 避免所有任务在同一分钟触发,分散系统压力
- 幂等性 - 任务多次执行结果应该一致,防止重复数据
- 超时设置 - 每个任务都要有超时限制,防止僵尸进程
- 失败告警 - 关键任务失败时立即通知,不要等用户发现
⚠️ 避坑指南
- 别把高频任务(每分钟)和低频任务(每天)放同一个 Agent,资源竞争会导致延迟
- 长任务用独立队列,别阻塞其他定时任务
- 任务之间如果有依赖关系,用工作流编排而非多个独立 cron
- 夏令时/冬令时切换时,注意 cron 表达式是否需要调整
监控与运维
# 查看所有定时任务
openclaw cron list
# 输出示例
NAME SCHEDULE AGENT STATUS NEXT RUN
seo-daily-report 0 8 * * * seo-agent active 2026-04-14 08:00
competitor-watch 0 */6 * * * research active 2026-04-14 06:00
social-post 0 10,14,18 * * content paused -
# 查看任务执行历史
openclaw cron history seo-daily-report
# 输出示例
TIME STATUS DURATION OUTPUT
2026-04-13 08:00:01 success 45s Report saved
2026-04-12 08:00:03 success 52s Report saved
2026-04-11 08:00:00 failed 30s Network timeout
# 暂停/恢复任务
openclaw cron pause social-post
openclaw cron resume social-post
# 删除任务
openclaw cron remove competitor-watch
任务健康检查脚本
#!/bin/bash
# health-check.sh - 定时任务健康检查
echo "=== OpenClaw Cron 健康检查 ==="
# 检查 Gateway 状态
openclaw gateway status || exit 1
# 检查任务列表
JOBS=$(openclaw cron list --format json)
TOTAL=$(echo $JOBS | jq '. | length')
ACTIVE=$(echo $JOBS | jq '[.[] | select(.status=="active")] | length')
FAILED=$(echo $JOBS | jq '[.[] | select(.lastRun.status=="failed")] | length')
echo "总任务数: $TOTAL"
echo "活跃任务: $ACTIVE"
echo "最近失败: $FAILED"
# 如果有失败任务,发送告警
if [ $FAILED -gt 0 ]; then
echo "⚠️ 检测到 $FAILED 个失败任务"
curl -X POST "$WEBHOOK_URL" \
-H "Content-Type: application/json" \
-d "{\"text\":\"⚠️ Cron任务告警: $FAILED 个任务最近执行失败\"}"
fi
echo "检查完成 ✅"