javascriptcronelectronnode-cron

Trouble with cron job scheduling based on activity


I've got a cron.schedule function here that runs the code once every second. When the user is on the website, it displays "In website" and when they enter a game, it shows "In game" However, when the user is in the game, it stops the cron.schedule, so the code doesn't run every second when the user returns to the website. Any help will be appreciated.

The checkGameStatus() function returns either true or false. true being in the user is in the website, false being the user being in game.

let task = cron.schedule("* * * * * *", async () => {
    let isWebsite = await checkGameStatus();
    if (isWebsite) {
        task.start();
        console.log("In website")
    } else {
        task.stop();
        //ipcRenderer.send("trackgame", game, placeid)
        console.log("In game")
    }
});

Any help will be appreicated!
Note: This is a electron project


Solution

  • Don't stop the task. Use a global variable to keep the state so you can detect transitions.

    let websiteState = false;
    let task = cron.schedule("* * * * * *", async() => {
      let isWebsite = await checkGameStatus();
      if (websiteState != isWebsite) {
        if (isWebsite) {
          console.log("In website")
        } else {
          console.log("In game")
        }
        websiteState = isWebsite;
      }
    });