title: OpenCLAW 定时任务设置 - 自动化运营入门指南 tags: [自动化, 定时任务, cron, 入门]


OpenCLAW 定时任务设置 - 自动化运营入门指南

详细介绍 OpenCLAW 定时任务的配置方法,帮助你实现 Agent 的自动化运行。

什么是定时任务?

定时任务(Scheduled Task)是让 Agent 在指定时间自动执行任务的机制。通过定时任务,你可以:

  • 定时发送报告或通知
  • 定时抓取网页数据
  • 定时执行数据同步
  • 定时发布内容到社交媒体
  • 定时清理临时文件
  • 定时监控系统状态

定时任务基础

Cron 表达式入门

OpenCLAW 使用 Cron 表达式定义执行时间:

┌───────────── 分钟 (0 - 59)
│ ┌───────────── 小时 (0 - 23)
│ │ ┌───────────── 日期 (1 - 31)
│ │ │ ┌───────────── 月份 (1 - 12)
│ │ │ │ ┌───────────── 星期 (0 - 6, 0 = 周日)
│ │ │ │ │
* * * * *

常用 Cron 表达式

表达式 含义 示例
* * * * * 每分钟 持续监控
0 * * * * 每小时整点 每小时执行
0 9 * * * 每天早上9点 每日简报
0 9 * * 1-5 工作日早上9点 工作日提醒
0 */2 * * * 每2小时 定期同步
0 0 1 * * 每月1日午夜 月度报告

配置定时任务

方式一:YAML 配置文件

# schedules.yaml
schedules:
  # 每日早间简报
  - name: daily-briefing
    description: 每日早上发送简报
    cron: "0 8 * * *"
    enabled: true

    # 要执行的 Agent
    agent: my-agent

    # 执行的任务
    task:
      type: message
      channel: slack
      content: "早上好!开始新的一天"

  # 每小时数据同步
  - name: hourly-sync
    description: 每小时同步数据
    cron: "0 * * * *"
    enabled: true
    agent: sync-agent

    task:
      type: script
      path: ./scripts/sync_data.py

  # 每周报告
  - name: weekly-report
    description: 每周生成报告
    cron: "0 18 * * 5"
    enabled: true
    agent: report-agent

    task:
      type: workflow
      name: generate-weekly-report

方式二:命令行配置

# 创建定时任务
openclaw schedule create \
  --name daily-briefing \
  --cron "0 8 * * *" \
  --agent my-agent \
  --task-type message \
  --task-params '{"channel": "slack", "content": "早上好"}'

# 列出所有定时任务
openclaw schedule list

# 启用/禁用定时任务
openclaw schedule enable daily-briefing
openclaw schedule disable daily-briefing

# 删除定时任务
openclaw schedule delete daily-briefing

方式三:代码配置

from openclaw.scheduler import Schedule, Task

# 创建定时任务
schedule = Schedule(
    name="daily-briefing",
    cron="0 8 * * *",
    agent="my-agent",
    task=Task(
        type="message",
        channel="slack",
        content="早上好!开始新的一天"
    )
)

# 保存配置
schedule.save()

# 或者使用装饰器
@schedule.cron("0 8 * * *")
def daily_briefing():
    agent = Agent("my-agent")
    agent.send_message(channel="slack", content="早上好!")

定时任务类型

1. 消息通知任务

- name: daily-notification
  cron: "0 9 * * *"
  agent: notification-agent

  task:
    type: message

    # 消息渠道
    channel: slack  # slack, email, webhook, feishu

    # 消息内容
    content: |
      📊 每日数据报告

      新增用户: 120
      活跃用户: 3,450
      收入: ¥15,680

    # 接收者
    recipients:
      - user: admin
      - channel: #general

2. 数据抓取任务

- name: competitor-analysis
  cron: "0 */4 * * *"  # 每4小时
  agent: crawler-agent

  task:
    type: workflow
    name: competitor-crawl

    params:
      targets:
        - https://competitor1.com
        - https://competitor2.com

      output:
        path: ./data/competitors
        format: json

      options:
        depth: 2
        concurrency: 5

3. 数据处理任务

- name: data-processing
  cron: "0 2 * * *"  # 每天凌晨2点
  agent: processor-agent

  task:
    type: script
    path: ./scripts/process_data.py

    args:
      input: ./data/raw
      output: ./data/processed
      config: ./config/process.yaml

    env:
      PYTHON_ENV: production
      DEBUG: "false"

4. 备份任务

- name: daily-backup
  cron: "0 3 * * *"  # 每天凌晨3点
  agent: backup-agent

  task:
    type: workflow
    name: full-backup

    params:
      targets:
        - ./data
        - ./configs
        - ./memory

      destination: s3://bucket/backups

      compression: gzip
      retention_days: 30

高级配置

执行超时设置

- name: long-task
  cron: "0 1 * * *"

  # 超时配置
  timeout:
    enabled: true
    seconds: 3600  # 1小时
    on_timeout: skip  # skip | retry | notify

  # 重试配置
  retry:
    enabled: true
    max_attempts: 3
    delay: 300  # 5分钟
    backoff: exponential

条件执行

- name: conditional-task
  cron: "0 8 * * *"

  # 条件判断
  conditions:
    # 工作日才执行
    - type: day_of_week
      operator: in
      value: [1, 2, 3, 4, 5]

    # 股票交易日才执行
    - type: custom
      script: |
        import trading_calendars
        return trading_calendars.is_trading_day(date.today())

  # 满足条件才执行
  skip_if_conditions_fail: true

任务依赖

- name: pipeline-task
  cron: "0 */2 * * *"

  # 任务依赖
  dependencies:
    - task: data-fetch
      required: true

    - task: data-clean
      required: true

    - task: data-analyze
      requires: [data-fetch, data-clean]

  # 执行顺序
  execution_order:
    - data-fetch
    - data-clean
    - data-analyze

并发控制

- name: concurrent-task
  cron: "0 * * * *"

  # 并发控制
  concurrency:
    max_instances: 1    # 最多1个实例
    queue_policy: skip   # skip | wait | cancel

  # 防止重复执行
  idempotency:
    enabled: true
    key: "${date}-task-name"
    window: 3600  # 1小时内不重复

监控与管理

查看任务执行

# 查看任务列表
openclaw schedule list

# 查看任务详情
openclaw schedule info daily-briefing

# 查看执行历史
openclaw schedule history daily-briefing --limit 10

# 查看执行日志
openclaw schedule logs daily-briefing --tail 100

任务状态监控

# 实时监控任务执行
openclaw schedule monitor

# 输出示例
# ┌─────────────────┬────────────┬─────────┬──────────┐
# │ 任务名称        │ 状态       │ 下次执行│ 上次执行 │
# ├─────────────────┼────────────┼─────────┼──────────┤
# │ daily-briefing  │ ✓ 运行中   │ 08:00   │ 07:59    │
# │ hourly-sync     │ ✓ 等待中   │ 09:00   │ 08:00    │
# │ weekly-report   │ ⚠ 禁用    │ Friday  │ -        │
# └─────────────────┴────────────┴─────────┴──────────┘

手动触发

# 手动执行任务
openclaw schedule run daily-briefing

# 带参数执行
openclaw schedule run daily-briefing --params '{"key": "value"}'

告警配置

执行失败告警

- name: critical-task
  cron: "0 * * * *"

  # 告警配置
  alerts:
    on_failure:
      - type: email
        to: admin@example.com

      - type: slack
        channel: "#alerts"
        message: "任务执行失败!"

    on_timeout:
      - type: webhook
        url: https://hooks.example.com/alerts

    on_retry:
      - type: log
        level: warning

健康检查

- name: health-check
  cron: "*/5 * * * *"  # 每5分钟

  task:
    type: health_check

  alerts:
    missed_runs:
      threshold: 2
      notify:
        - type: email

完整配置示例

# schedules.yaml
schedules:
  - name: daily-operations
    description: 日常运营任务集合
    cron: "0 9 * * *"
    enabled: true

    # Agent 配置
    agent: operations-agent

    # 超时和重试
    timeout:
      enabled: true
      seconds: 1800

    retry:
      enabled: true
      max_attempts: 2

    # 告警
    alerts:
      on_failure:
        - type: slack
          channel: "#operations"

    # 日志
    logging:
      enabled: true
      level: info
      retention_days: 30

    # 任务定义
    task:
      type: workflow
      name: daily-operations

      steps:
        - name: sync-data
          script: ./scripts/sync.sh

        - name: generate-report
          script: ./scripts/report.py

        - name: send-notification
          message:
            channel: slack
            template: daily-report

最佳实践

1. 合理设置执行时间

# ❌ 多个任务同时执行
- name: task-1
  cron: "0 9 * * *"
- name: task-2
  cron: "0 9 * * *"  # 冲突!

# ✅ 错开执行时间
- name: task-1
  cron: "0 9 * * *"
- name: task-2
  cron: "30 9 * * *"  # 错开30分钟

2. 重要任务备份

- name: critical-task
  cron: "0 9 * * *"

  # 双重保障
  retry:
    enabled: true
    max_attempts: 3

  # 失败告警
  alerts:
    on_failure:
      - type: email
        to: admin@example.com

3. 资源规划

- name: heavy-task
  cron: "0 2 * * *"  # 凌晨执行

  # 资源限制
  resources:
    max_memory: 2GB
    max_cpu: 50%
    priority: low

小结

本文详细介绍了 OpenCLAW 定时任务的设置方法:

  1. Cron 表达式 - 时间配置基础
  2. 配置方式 - YAML、命令行、代码
  3. 任务类型 - 消息、数据抓取、处理、备份
  4. 高级配置 - 超时、重试、条件、依赖、并发
  5. 监控管理 - 查看状态、执行历史、手动触发
  6. 告警机制 - 失败、超时、告警通知

继续学习: - 定时任务最佳实践 - 优化定时任务性能 - 定时任务故障排查 - 解决问题