首页 > 解决方案 > 在节点 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)

}) 

标签: node.jsrestexpresshttpsettimeout

解决方案


使用 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

}) 

推荐阅读