【问题标题】:Node.js do action when object date match/endsNode.js 在对象日期匹配/结束时执行操作
【发布时间】:2022-02-18 16:34:10
【问题描述】:
我正在做带有 end_date 参数的拍卖网站,我想在当前日期与 end_date 匹配时完成该拍卖。所以我想知道我可以使用的最佳解决方案是什么?我知道我可以使用“setInterval”每秒检查一次数据库,但这是最好的解决方案吗?也许有更好的主意,它监视日期而不定期检查 SQL?
我也无法使用静态日期(end_dates)启动流程,因为如果用户提出要约,end_date 会发生变化,因此节点必须“实时”监控它。
【问题讨论】:
标签:
sql
node.js
time
monitoring
live
【解决方案1】:
我会这样做:
服务器
客户
- 客户端将始终收到
end_date 值并显示auction finished 或still running 等。因此,如果任何用户打开选项卡,客户端可以正确地在浏览器中结束拍卖。这得到了一些 setInterval 或 setTimeout 要求正确显示倒计时、更新拍卖状态或阻止用户做事等的支持。
API
- 对于给定拍卖的每个请求,您需要检查数据库中设置的标志。只有在拍卖尚未完成的情况下才允许进行特定操作。
服务器启动时的伪代码
// 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)
}