我想在调用特定端点后延迟 1 小时或 5 小时触发 Express 应用中的函数。
我尝试在 enpoint 的 then
链中使用简单的 setTimeout
,并在 Controller 中使用类似的内容:
function(req, res, next) {
return mailer.sendEmail(req.user, 'firstEmail') // returns a promise
.then(function(emailResult) {
if (emailResult == 'ok') {
res.sendStatus(200).json({ message: 'You will receive an email in 1 hour' }) // set positive API json response
} else {
res.sendStatus(200).json({ message: 'You will receive an email in 5 hour' }) // set negative API json response
}
return emailResult
})
.then(function(emailResult){
return new Promise((resolve, reject) => {
setTimeout(function(){
return return mailer.sendEmail(req.user, 'secondEmail')
}, emailResult == 'ok' ? 60 * 60 * 1000 : 5 * 60 * 60 * 1000) // 1 hour or 5 hours
})
})
})
似乎有效,但我有两个主要疑问:
- 如果我使用 (pm2 startOrReload prod.json) 重新启动应用程序的 pm2 进程,所有超时都会被取消吗?
- 如果我在此系统中安排了 600 次超时,我会遇到性能问题吗?
有类似的经验吗?
最佳答案
像这样的超时可能是一种解决方案,但不是最好的解决方案。
如果超时立即增加您的内存,例如每小时,当您重新启动 Node.js 进程时,尚未触发的计时器将丢失,这意味着即使您尝试更新新的,也无法重新启动您的应用程序如果您不想丢失其中任何一个,请保存代码。丢失电子邮件或永远不会重新启动,有点困惑,对吧?
对于这种情况,最常实现的方法是消息队列。 您可以将消息队列视为在数据库中存储和消费的计时器,这样您就不必担心计时器是否会被取消或在您不希望发生时被多次调用。
RabbitMQ 是一个对 Node.js 友好的独立 MQ。
Kue 是一个类似 MQ 的 NPM 包,依赖于 Redis。
希望你喜欢它们。 ;)
关于node.js - Node/Express 应用程序中延迟超过一小时的触发功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53375170/