Search code examples
node.jsnode-cron

Node-Cron: how to ensure last job is complete


I am using node-cron to send operational emails (currently searching for new emails that need to be sent every minute).

My function (operationalEmails) looks for mongodb records that have a sent flag = false, sends the email, then changes the sent flag = true.

If an iteration of the cron has a large payload of records to send, it could take more than a minute.

How do I ensure the last iteration of the cron is complete before starting a new one?

//Run every Min
cron.schedule("* * * * *", () => {
  operationalEmails();
});

Solution

  • you would need to create a simple lock

    const running = false;
    
    function operationalEmails() {
    
       if (running) {
         return
       }
    
       running = true;
       // do stuff
       running = false;
    }
    
    //Run every Min
    cron.schedule("* * * * *", () => {
      operationalEmails();
    });