Node.js在对象日期匹配/结束时执行操作



我正在做一个有end_date参数的拍卖网站,我想在当前日期与end_date匹配时完成拍卖。所以我想知道我能使用的最好的解决方案是什么?我知道我可以使用";setInterval";每秒钟检查一次数据库,但这是最好的解决方案吗?也许还有一个更好的想法,即在不检查SQL的情况下监视日期?我也不能用静态日期(end_dates(开始这个过程,因为如果用户提出报价,end_date正在更改,所以节点必须监视它;生活";。

我会这样做:

服务器

  • 当服务器启动时,它会加载end_date一次。如果拍卖已经完成(并存储在数据库中(,那么什么也不做。如果它仍在运行,您可能需要设置一个setTimeout,它将在数据库中为给定的拍卖设置一个类似ended的标志。

  • 每当拍卖中的某些内容在数据库中从任何来源更改时,您都必须清除现有的超时并用新值重置它。

客户端

  • 客户端将始终接收end_date值,并显示auction finishedstill running等。因此,如果任何用户打开选项卡,客户端可以在浏览器中正确结束拍卖。这得到了一些setIntervalsetTimeout调用的支持,这些调用用于正确显示倒计时、更新拍卖状态或防止用户做事情等

API

  • 在给定的拍卖中,Foreach请求需要对照数据库中设置的标志进行检查。只有在拍卖尚未完成的情况下,才允许进行某个动作

服务器启动时的伪代码

// this assumes, that auction.end_date is a javascript date object.
// you may wanna adjust this to your envrionment. 
function setAuctionEndedTrigger(auction) {
// calculates remaining milliseconds till auction will end.
const remaining_time = auction.end_date.getTime() - Date.now()
setTimeout(() => {
// store in the database that the auction has ended!
// 1 for true and 0 for false.
sql.execute(`update auctions set ended=1 where id = '${auction.id}'; `)

}, remaining_time)
}

// Code ecexuted when server starts
// Pseudocode... 
// load auctions from db which have not already ended:
const auctions = await sql.execute('select * from auctions where ended is null OR ended = 0;')
// for each running auction set a trigger! 
for(let auction of auctions) {
setAuctionEndedTrigger(auction)
}

最新更新