[英]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.