【问题标题】: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。如果拍卖已经完成(并存储在数据库中),那么什么也不做。如果它仍在运行,您可能需要设置一个setTimeout,它将在数据库中为给定的拍卖设置一个类似ended 的标志,此时拍卖完成。

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

    客户

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

    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)
    }
    
    

    【讨论】:

      猜你喜欢
      • 2012-01-14
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 2020-08-27
      • 2017-10-20
      • 1970-01-01
      相关资源
      最近更新 更多