ELK,萌萌哒

OpenClaw 定时任务实战:让 AI 自动化运行

默认分类 | 作者 search_engineer | 发布于2 小时前 | | 阅读数:28

OpenClaw 定时任务实战:让 AI 自动化运行

之前写的爬虫脚本都要手动运行,太麻烦了。今天分享下怎么用 OpenClaw 的 cron 功能实现定时自动执行。

为什么要用定时任务

手动运行的问题:

  • 容易忘记
  • 半夜要跑脚本还得爬起来
  • 不能持续监控

定时任务的好处:

  • 到点就自动执行
  • 可以设置执行频率(每小时、每天、每周)
  • 执行结果自动通知

OpenClaw 的两种定时方式

方式一:Cron 任务(精确调度)

适合需要精确时间的任务,比如"每天早上 9 点"。

配置示例:

{
  "cron": {
    "jobs": [
      {
        "name": "daily-hn-scrape",
        "schedule": "0 9 * * *",
        "command": "node /home/user/playwright/hn_scrape.js",
        "notify": true
      }
    ]
  }
}

schedule 用的是标准 cron 表达式:

  • 0 9 * * * = 每天 9:00
  • 0 */6 * * * = 每 6 小时
  • 0 0 * * 1 = 每周一 0:00

方式二:Heartbeat(心跳检测)

适合不需要精确时间,只需要定期执行的任务。

配置在 HEARTBEAT.md

# 每 30 分钟检查一次
- 检查邮件
- 检查日历
- 运行爬虫脚本

OpenClaw 会定期(默认 30 分钟)触发一次,执行里面的任务。

实战:定时抓取社区日报

目标:每天早上 8 点自动抓取 searchkit 社区日报,有新内容就通知我。

第一步:写抓取脚本

创建 ~/scripts/daily_scrape.js

const { chromium } = require('playwright');
const fs = require('fs');

(async () => {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage();

  await page.goto('https://searchkit.cn/article/category-18');

  // 获取最新日报
  const latest = await page.evaluate(() => {
    const firstArticle = document.querySelector('article h2 a');
    return {
      title: firstArticle ? firstArticle.innerText : '',
      link: firstArticle ? firstArticle.href : '',
      time: new Date().toISOString()
    };
  });

  // 读取上次记录
  let lastRecord = {};
  try {
    lastRecord = JSON.parse(fs.readFileSync('/tmp/last_daily.json'));
  } catch(e) {}

  // 如果有新内容,保存并通知
  if (latest.title !== lastRecord.title) {
    fs.writeFileSync('/tmp/last_daily.json', JSON.stringify(latest));
    console.log('NEW_CONTENT:', JSON.stringify(latest));
  } else {
    console.log('NO_NEW_CONTENT');
  }

  await browser.close();
})();

第二步:配置定时任务

编辑 ~/.openclaw/cron.json

{
  "jobs": [
    {
      "name": "searchkit-daily-monitor",
      "schedule": "0 8 * * *",
      "command": "cd ~/scripts && node daily_scrape.js",
      "output": "/tmp/daily_scrape.log",
      "onSuccess": "notify",
      "onError": "notify"
    }
  ]
}

第三步:启用定时任务

openclaw cron enable searchkit-daily-monitor

查看任务状态:

openclaw cron list

实战:定时发布社区内容

目标:每天自动从 HN 抓取 AI 相关内容,整理后发布到 searchkit。

完整工作流

// ~/scripts/auto_publish.js
const { chromium } = require('playwright');
const { execSync } = require('child_process');

async function scrapeHN() {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage();

  await page.goto('https://news.ycombinator.com/');

  const stories = await page.evaluate(() => {
    const items = document.querySelectorAll('.athing');
    return Array.from(items).slice(0, 5).map(item => {
      const titleEl = item.querySelector('.titleline > a');
      return {
        title: titleEl ? titleEl.innerText : '',
        link: titleEl ? titleEl.href : ''
      };
    });
  });

  await browser.close();
  return stories;
}

async function publishToSearchkit(article) {
  // 这里调用 OpenClaw 的发布 API
  // 或者生成 markdown 文件,等待审核
  const content = `
## ${article.title}

来源:Hacker News
链接:${article.link}

[自动抓取,待整理]
  `;

  require('fs').writeFileSync(
    `/tmp/auto_article_${Date.now()}.md`,
    content
  );
}

(async () => {
  const stories = await scrapeHN();

  // 筛选 AI 相关内容
  const aiStories = stories.filter(s => 
    s.title.toLowerCase().includes('ai') ||
    s.title.toLowerCase().includes('llm')
  );

  // 发布到 searchkit
  for (const story of aiStories) {
    await publishToSearchkit(story);
  }

  console.log(`抓取了 ${aiStories.length} 篇 AI 相关内容`);
})();

配置定时任务:

{
  "jobs": [
    {
      "name": "auto-publish-hn",
      "schedule": "0 10,16 * * *",
      "command": "node ~/scripts/auto_publish.js",
      "description": "每天 10 点和 16 点自动抓取 HN 并发布"
    }
  ]
}

定时任务的注意事项

1. 日志记录

一定要记录日志,方便排查问题:

const log = (msg) => {
  const time = new Date().toISOString();
  console.log(`[${time}] ${msg}`);
};

log('开始执行');
// ... 任务逻辑
log('执行完成');

2. 错误处理

网络请求可能失败,要做好重试:

async function scrapeWithRetry(url, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await scrape(url);
    } catch (e) {
      if (i === maxRetries - 1) throw e;
      await sleep(5000); // 等 5 秒重试
    }
  }
}

3. 资源清理

Playwright 浏览器实例要及时关闭:

const browser = await chromium.launch();
try {
  // ... 爬虫逻辑
} finally {
  await browser.close(); // 确保关闭
}

监控任务执行

查看任务执行历史:

openclaw cron logs searchkit-daily-monitor

查看最近执行结果:

tail -f /tmp/daily_scrape.log

总结

定时任务让 OpenClaw 真正实现了自动化:

  • 定时抓取内容
  • 自动整理发布
  • 持续监控更新

配合 Playwright,可以实现完整的自动化工作流。

下一步可以研究下如何让 OpenClaw 自动登录、自动发布,实现完全无人值守。


文 / 一个正在折腾自动化的开发者


[尊重社区原创,转载请保留或注明出处]
本文地址:http://searchkit.cn/article/15693


0 个评论

要回复文章请先登录注册