简体   繁体   English

如何使用mongodb中的时间戳在特定时间触发函数?

[英]How to trigger a function on a certain time using timestamps from mongodb?

Let's say i am storing some timestamps in my MongoDB, each timestamp indicates a time when some certain function should be run. 假设我在MongoDB中存储了一些时间戳,每个时间戳都表示应该运行某些特定功能的时间。

I am not sure what should be the correct approach to this since I am new in backend developing. 我不知道什么是正确的方法,因为我是后端开发的新手。

Mongo data structure goes like this(this is just an example): Mongo数据结构如下所示(这只是一个示例):

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

and on this certain time I want to trigger a function: 在这个特定的时间,我想触发一个函数:

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

You need to change the format of timestamp you get from mongodb into something like this - "13 Sept 2019 18:39:40" or "2019-01-01 00:00:00". 您需要将从mongodb获得的时间戳格式更改为类似以下内容:“ 13 Sept 2019 18:39:40”或“ 2019-01-01 00:00:00”。 Then you need to parse the timestamp you get from mongodb using this Date.parse() 然后,您需要使用此Date.parse()解析从mongodb获取的时间戳。

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

Once that is done you need to get difference between timestamp and current time and use that difference in a setTimeout() function, which takes 2 parameters - function to be run and time in milliseconds 完成此操作后,您需要获取时间戳记当前时间之间的差,并在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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据数据库中的时间戳触发事件 - mongodb - How to trigger events based on time stamp from database - mongodb 如何使用给定的时间戳在 mongodb 中查找每天的最后一条记录? - How to find last record of each day in mongodb using given timestamps? 根据 MongoDB 记录中的时间值在某个时间运行 function - Run function at certain time based on time value in MongoDB record 如何在一定时间后触发 throw 指令? - How can you trigger a throw instruction after a certain time? mongoDB时间字段触发器? - mongoDB Time-field Trigger? 如何向 MongoDB 中的现有记录添加时间戳 - How to add timestamps to existing records in MongoDB 将 Mongodb 集合中的实例保存为 Atlas 触发器函数中的字符串变量 - Save instances from Mongodb collection as string variables in an Atlas Trigger Function 如何使用 mongoose 和 node.js 将 mongodb 时间戳转换为 dd-mm-yyyy 格式? - How to convert mongodb timestamps to dd-mm-yyyy format using mongoose and node.js? 在MongoDB聚合函数中使用$ project在$ group之后返回某些数据 - Using $project in MongoDB aggregate function to return certain data after $group 如何使用 NodeJS express 框架从 MongoDB 中搜索关键字(错误:MongoDB schema.index 不是函数) - How to search keywords from MongoDB using NodeJS express framework (Error: MongoDB schema.index is not a function)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM