导读:凌晨3点还在手动跑数据?让OpenClaw的定时任务系统帮你搞定。本教程从Cron基础到高级调度,带你实现真正的自动化运营。
📋 功能介绍
OpenClaw内置强大的Cron系统,支持:
- 标准Cron - 支持标准5段Cron表达式
- 自然语言 - "每天上午9点"也能识别
- 时区支持 - 可为每个任务指定时区
- 任务链 - 任务完成后触发下一个任务
- 重试机制 - 失败自动重试,可配置策略
- 执行历史 - 完整的执行记录和日志
- 并发控制 - 防止任务重复执行
🔧 Cron表达式速查
* * * * *
│ │ │ │ │
│ │ │ │ └── 星期 (0-7, 0和7都是周日)
│ │ │ └──── 月份 (1-12)
│ │ └────── 日期 (1-31)
│ └──────── 小时 (0-23)
└────────── 分钟 (0-59)
常用表达式:
"0 9 * * *" # 每天9:00
"0 */2 * * *" # 每2小时
"0 9 * * 1-5" # 工作日9:00
"0 0 1 * *" # 每月1号0:00
"*/5 * * * *" # 每5分钟
✍️ 创建定时任务
方式一:使用openclaw命令
# 添加定时任务
openclaw cron add \
--name "daily-news" \
--schedule "0 9 * * *" \
--skill "web-search" \
--input '{"query": "AI news today", "count": 5}'
# 使用自然语言
openclaw cron add \
--name "weekly-report" \
--schedule "every Monday at 9am" \
--workflow "weekly-analytics.yaml"
方式二:YAML配置文件
# ~/.openclaw/cron/jobs.yaml
jobs:
- name: morning-news
schedule: "0 8 * * *"
timezone: "Asia/Shanghai"
enabled: true
action:
type: skill
name: web-search
input:
query: "今日AI新闻"
sources: ["techcrunch", "github"]
on_success:
action: notify
message: "新闻收集完成"
on_error:
action: email
to: "admin@company.com"
retry:
count: 3
delay: 5m
- name: backup-data
schedule: "0 2 * * *"
concurrency: forbid # 防止重叠执行
action:
type: script
file: "/scripts/backup.sh"
方式三:JavaScript API
const { cron } = require('openclaw');
// 创建定时任务
const job = await cron.add({
name: 'data-sync',
schedule: '0 */6 * * *',
timezone: 'America/New_York',
handler: async () => {
// 自定义逻辑
const data = await fetchData();
await processData(data);
await sendNotification('同步完成');
},
options: {
retry: {
attempts: 3,
backoff: 'exponential'
}
}
});
// 暂停任务
await cron.pause('data-sync');
// 恢复任务
await cron.resume('data-sync');
// 删除任务
await cron.remove('data-sync');
🎯 实战案例库
案例1:每日数据备份
jobs:
- name: daily-backup
schedule: "0 3 * * *"
action:
type: skill-chain
steps:
- skill: db-dump
input:
database: "production"
output: "/backup/db_{{date}}.sql"
- skill: s3-upload
input:
file: "/backup/db_{{date}}.sql"
bucket: "backups"
- skill: cleanup
input:
path: "/backup"
keep: 7 # 保留7天
案例2:网站健康检查
jobs:
- name: health-check
schedule: "*/5 * * * *" # 每5分钟
action:
type: skill
name: http-check
input:
urls:
- "https://mysite.com"
- "https://api.mysite.com"
timeout: 10
on_error:
action: skill
name: alert-sender
input:
channels: ["email", "slack"]
message: "🚨 网站异常:{{error.message}}"
案例3:社交媒体自动化
jobs:
- name: auto-tweet
schedule: "0 10,15,20 * * *" # 每天3次
action:
type: workflow
file: "social-media.yaml"
vars:
platform: "twitter"
content_source: "latest-blog"
- name: weekly-report-tweet
schedule: "0 9 * * 1" # 每周一上午9点
action:
type: skill
name: social-poster
input:
platform: "twitter"
content_template: |
📊 本周数据报告:
- 新增用户:{{metrics.new_users}}
- 活跃用户:{{metrics.active_users}}
- 收入增长:{{metrics.revenue_growth}}%
案例4:竞品价格监控
jobs:
- name: price-monitor
schedule: "0 */4 * * *" # 每4小时
action:
type: skill-chain
steps:
- skill: browser
name: scrape-prices
input:
urls:
- "https://competitor1.com/product"
- "https://competitor2.com/product"
selector: ".price"
- skill: price-comparer
name: compare
input:
threshold: 0.05 # 5%变化阈值
- skill: alert-sender
condition: "{{steps.compare.changed}}"
input:
message: "💰 价格变动 detected!"
✅ 最佳实践
- 避免任务重叠 - 设置concurrency: forbid,防止长任务重复执行
- 合理设置超时 - 为每个任务设置合理的timeout
- 完善错误处理 - 配置on_error回调,及时发现问题
- 记录执行日志 - 启用详细日志,便于排查
- 测试再上线 - 先用测试环境验证任务逻辑
- 监控任务状态 - 定期review任务执行历史
- 分散执行时间 - 避免所有任务在同一分钟执行
🔍 任务管理命令
# 列出所有任务
openclaw cron list
# 查看任务详情
openclaw cron show daily-news
# 查看执行历史
openclaw cron history daily-news --limit 20
# 手动触发任务
openclaw cron run daily-news
# 暂停任务
openclaw cron pause daily-news
# 恢复任务
openclaw cron resume daily-news
# 删除任务
openclaw cron remove daily-news
# 编辑任务
openclaw cron edit daily-news
📊 监控与告警
jobs:
- name: important-task
schedule: "0 */6 * * *"
monitoring:
enabled: true
alert_after: 2 # 连续2次失败告警
notify_channels:
- email: "admin@company.com"
- slack: "#alerts"
- webhook: "https://hooks.slack.com/..."
action:
...
⚠️ 注意:定时任务在Docker中运行时,需要确保容器是持续运行的,或使用--restart=always策略。