简体   繁体   English

一定时间后,node.js发出事件

[英]node.js emit event after certain time

I have a database that has data inserted to it with a timestamp. 我有一个带有时间戳的数据插入数据库。 Once this timestamp is more than 24 hours before the current time I want an event to be emitted that causes the data to be deleted since it has been expired. 一旦此时间戳记比当前时间早24小时以上,我希望发出一个事件,该事件导致数据由于过期而被删除。

How can this be done? 如何才能做到这一点? I am running a http server so I can't afford constant checks since it would slow down each request and if a large amount of information accumulates it would take a long time to check each and every one. 我正在运行http服务器,因此我无法进行持续的检查,因为它会使每个请求变慢,并且如果大量信息积累,检查每个请求都将花费很长时间。 I also want to avoid having to spawn a child process if at all possible. 我还想避免尽可能地产生子进程。

Any ideas? 有任何想法吗?

You can use node-schedule to schedule jobs (arbitrary functions) for execution at specific dates. 您可以使用节点计划来计划要在特定日期执行的作业(任意函数)。

For example, the following would run a function 24 hours from the time it was invoked: 例如,以下代码将在调用函数后的24小时内运行该函数:

var schedule = require('node-schedule');
var futureDate = new Date(new Date().getTime() + 60 * 60 * 24 * 1000); // This is 24 hours from *now*

var j = schedule.scheduleJob(futureDate, function(){
  console.log('Do your work here.');
});

您想从数据库中删除数据,为什么不使用crontab?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM