节点 Cron:执行单个操作后添加 3 秒的延迟

Node Cron : Add a delay of 3sec after performing a single action

我正在向用户批量发送大量消息并使用 node-cron。消息发送给用户后,he/she 会收到电子邮件通知。我想在发送新消息之前添加 3 秒的延迟。

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