【问题标题】:How to trigger a function on a certain time using timestamps from mongodb?如何使用来自 mongodb 的时间戳在特定时间触发函数?
【发布时间】:2023-03-27 08:53:02
【问题描述】:

假设我在我的 MongoDB 中存储了一些时间戳,每个时间戳表示应该运行某个特定函数的时间。

由于我是后端开发的新手,因此我不确定应该采取什么正确的方法。

Mongo 数据结构是这样的(这只是一个例子):

{id: 115155, userId: 152115, timestamp: 13-09-2019:15:30:00}

在这个特定的时间我想触发一个函数:

someFunction(eventId, userId){ ...something here }

【问题讨论】:

    标签: node.js mongodb typescript express


    【解决方案1】:

    您需要将您从 mongodb 获得的时间戳格式更改为“2019 年 9 月 13 日 18:39:40”或“2019-01-01 00:00:00”。然后您需要使用此 Date.parse() 解析从 mongodb 获得的时间戳

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

    完成后,您需要获取 timestamp当前时间 之间的差异,并在 setTimeout() 函数中使用该差异,该函数需要 2 个参数 - 要运行的函数以毫秒为单位的时间

        let timediff = new Date() - Date.parse("2019-09-13 18:54:50");
    
        setTimeout(function() { 
            console.log("Called when current time = mongodb timestamp"); 
        }, timediff);
    

    【讨论】:

    • 我知道时间格式不对,这只是一个例子,我不能为我存储的每个时间戳写一个这样的函数,有数百个..
    • 你不必重写函数,你可以有一个单独的模块来处理这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 2012-08-27
    • 2023-04-02
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    相关资源
    最近更新 更多