Reputation: 21
I have to run an async function written with Puppeteer (it's a bot) and I want to run that function every 60 seconds. The issue is that the async function (bot) runs for 2 min and so node cron automatically executes another async function which leads to 2 bot and 5s later it will launch another instance of this function.
What i want is to run 1st time then wait for 60s And after that execute it again. I'm so confused, it's my first NodeJS project.
const cron = require("node-cron")
cron.schedule("*/60 * * * * *", async () => {
try {
console.log(BotVote("Royjon94", "1"))
}
catch {
console.log('error 404')
}
})
Upvotes: 2
Views: 4277
Reputation: 10790
I'm not sure cron
is suitable for this kind of job. But basically you can achieve the same behavior with a basic while loop and a promise to await.
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();
Upvotes: 3