1

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();
});
Josh J
  • 59
  • 7

1 Answers1

1

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();
});
Chris
  • 2,296
  • 4
  • 27
  • 46
  • 1
    Ahh, easy enough! I made one update since operationEmails is a function I am importing: var opEmailsRunning = false; const runOpEmails = async () => { if (!opEmailsRunning) { opEmailsRunning = true; await operationalEmails(); opEmailsRunning = false; } else { return; } }; //Run every Min cron.schedule("* * * * *", () => { runOpEmails(); }); – Josh J Dec 17 '20 at 21:36