Node-Cron: how to ensure last job is complete

1.2k views Asked by At

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();
});
1

There are 1 answers

1
Chris On BEST ANSWER

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();
});