I am sending bulk messages to users in batches and using node-cron. Once the message is sent to the user, he/she receives the email notification. I want to add a delay of 3sec before sending a new message.
public bulkActionHandler = async () => {
try {
const messageJobs: Array<IBulkAction> | null = await BulkAction.find({ isDeleted: 0, action: "message", isCompleted: 0 }).sort({dateCreated:1}).limit(1).exec()
if (messageJobs && messageJobs.length) {
for (let index = 0; index < messageJobs.length; index++) {
const element: IBulkAction = messageJobs[index];
if (element && element._id) {
const { error }: any = await this.messageHandler(element.data)
await BulkAction.findByIdAndUpdate({ _id: element._id }, {
isCompleted: !error ? 1 : 0,
status: !error ? 1 : 0
}).exec()
logger.info("Cron execution completed for " + element._id)
if (error) {
logger.error(JSON.stringify(error))
}
}
}
}
await BulkAction.deleteMany({isCompleted:1, status:1, dateCreated:{$lt:new Date(Date.now() - 24*60*60 * 1000)}}).exec()
} catch (error) {
logger.error(prepareErrorLog(error,'Something went wrong with bulk cron '))
}
}
const wait = (ms: number) => new Promise(res => setTimeout(res, ms));
// add wait into your fn
await wait(3000);