javascript - 使用 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')
}
})
解决方案
我不确定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();
推荐阅读
- javascript - 如何将 Chromium 中地址栏和选项卡的外观更改为与所附图像相似
- python - 带有三元运算符的海象运算符的正确语法是什么?
- python-3.x - 如何在一个“尝试”块中引发同一错误的多个异常
- powershell - 通过 power shell 脚本从 Outlook 中删除基于主题的邮件
- javascript - React 本机状态未使用 animated.start() 中的钩子更新
- hyperledger-fabric - 在超级账本结构中使用 Solidity 智能合约
- sql - 如何从另一个表插入更新数据?
- java - Spring MVC:通过 REST 端点将字符串日期转换为日期
- android - 未解决参考
- r - geom_text 删除其他几何图形(geom_point 和 geom_line)