Thursday, February 8, 2024

[SOLVED] How to make a delay inside cron on node js

Issue

I am using node js with the node-cron library. I need to make a delay in executing the code inside the cron. I tried await and setInterval, but the second cron function is not executed. What can be done?

cron.schedule("*/10 * * * * *", async function() {
  FakeGames.StartGame();
  await wait(3000);
  FakeGames.StopGame()
});

Solution

You can use settimeout, like this, so your FakeGames.stopGame() will execute after a certain dealy

    cron.schedule("*/10 * * * * *", function () {
      return new Promise((resolve, reject) => {
         FakeGames.StartGame();
         setTimeout(() => {
           FakeGames.StopGame();
         resolve();
       }, delayInMilliSeconds);
     });
   });



Answered By - Shankar Regmi
Answer Checked By - Timothy Miller (WPSolving Admin)