I have this function which is used to check every second if the current time matches the time of a scheduled email using cron.schedule. However, when it reaches the right time the sendEmail function runs 20+ times as well as the sql query all within a second.
the emails array is structured like this: [[time, address, subject, message, id], [time, address, subject, message, id]...]
code:
function send() {
for (let i = 0; i < emails.length; i++) {
let emailTime = emails[i][0];
let recipient = emails[i][1];
let subject = emails[i][2];
let message = emails[i][3];
let emailId = emails[i][4];
if (emailTime.split(' ')[1] == '24') { // cron only supports hours 1-23
let emailTimeSplit = emailTime.split(' ');
emailTimeSplit.splice(1, 1, '1');
emailTime = emailTimeSplit.join(' ');
}
cron.schedule(emailTime + ' *', () => {
sendEmail(recipient, subject, message); //asnychronous function in another script
var sql = `DELETE FROM emails WHERE email_id=${emailId}`;
con.query(sql, function (err, result) { //deletes email details from sql table
if (err) throw err;
console.log('items removed!');
});
});
}
}
setInterval(send, 1000);
I tried removing removing the email from the emails array using splice() which somehow made the problem worse and I tried skipping over an email that's already been sent using continue; statements but that resulted in running even more times.
Any help would be greatly appreciated