Search code examples
javascriptnode.jseventstimeouteventemitter

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.

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. I also want to avoid having to spawn a child process if at all possible.

Any ideas?


Solution

  • 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:

    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.');
    });