具有Node Cron的异步功能

时间:2020-09-11 19:41:22

标签: javascript asynchronous async-await cron

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

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

const cron = require("node-cron")

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

1 个答案:

答案 0 :(得分:1)

我不确定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();

相关问题