首页 > 解决方案 > 使用 Node Cron 的异步函数

问题描述

我必须运行一个用 Puppeteer(它是一个机器人)编写的异步函数,并且我想每 60 秒运行一次该函数。问题是异步函数(bot)运行了 2 分钟,因此节点 cron 自动执行另一个异步函数,导致 2 个机器人,5 秒后它将启动该函数的另一个实例。

我想要的是第一次运行然后等待 60 秒,然后再次执行。我很困惑,这是我的第一个 NodeJS 项目。

const cron = require("node-cron")

cron.schedule("*/60 * * * * *", async () => {
    try {
        console.log(BotVote("Royjon94", "1"))
    }
    catch {
        console.log('error 404')
    }
})

标签: javascriptasynchronousasync-awaitcron

解决方案


我不确定cron是否适合这种工作。但基本上你可以通过一个基本的 while 循环和一个等待的承诺来实现相同的行为。

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function BotVote() {
  await new Promise(r => setTimeout(() => {
    console.log("voting");
    r();
  })) // for illusturation purpose  
}


async function worker() {
  let i = 0;
  let keepGoing = true;
  while (keepGoing) {
    await BotVote()
    await delay(600); // imagine it's 1minute.
    i++;
    if (i === 3) keepGoing = false; // decide when you stop
  }
}

worker();


推荐阅读