node.js - 在节点 js 中将响应发送到客户端后从 setTimeOut 执行代码是一种不好的做法吗?
问题描述
我想在响应发送到客户端后调用 setTimeOut 以在 3 分钟后更改数据库中的值,这有什么问题吗?
app.get("/route",(req,res,next) => {
// update value in db
// then send the value in the response
res.status(200).json({newValue : value}).end();
setTimeout(()=>{
// change the value in the db after 3 minutes
},180000)
})
解决方案
使用 for 做一些工作没有问题setTimeout
,但这是一个幼稚的解决方案。如果服务器宕机,任务将丢失。因此,更好的方法是使用一些调度程序,例如node-cron
每分钟运行一次,轮询数据库以查看是否有任何行符合条件。如果您将应用程序更改为这样的架构,那么您只需要向表中添加一行,其到期时间T+3 minutes
为
var cron = require('node-cron');
cron.schedule('* * * * *', () => {
console.log('running a task every minute');
/* Get entries from database table which has a timestamp < now and is unprocessed and act on those data */
// do the processing
// mark the row as processed
});
那么你的路线将只是
app.get("/route",(req,res,next) => {
// update value in db
// then send the value in the response
res.status(200).json({newValue : value}).end();
// write a row to database table with expiry now() + 3 minutes
})
推荐阅读
- javascript - 无法读取未定义的属性 setdefaults
- markdown - 如何在 MARKDOWN 语言中居中对齐文本?
- android - Updating ImageView with RecyclerView
- reactjs - react date picker text box typing disable
- javascript - Redirect to a new URL using C#/JavaScript and logout
- microservices - Could not find file '/app/"Dynamic path which user selects picture"' in .net core web api
- java - iterable.iterator().hasNext() 在模拟行为后返回 false
- core-plot - 一系列绘图的 Coreplot 动画
- arrays - 在数组中查找缺失值的算法......到位了吗?
- python - 我如何让这个不和谐机器人向特定频道发送消息?