【问题标题】:Async Functions with Node Cron使用 Node Cron 的异步函数
【发布时间】:2020-09-12 10:33:39
【问题描述】:

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

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

const cron = require("node-cron")

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

【问题讨论】:

  • 好吧,我不知道节点中的 cron,但你不是在等待 BotVote 函数。如果该函数执行异步操作,您应该等待。

标签: javascript asynchronous async-await cron


【解决方案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();

【讨论】:

  • Eldar,非常感谢您的回复,我已经尝试过了,它可以按我的意愿工作。非常感谢您的帮助,祝您有美好的一天。
猜你喜欢
  • 2019-04-01
  • 2015-02-20
  • 2020-06-01
  • 2018-05-15
  • 2017-06-01
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多