Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Trigger Events in Node JS when a future date, time stored in Database is reached?

I am providing a functionality to the users where "They select a near future time, date while giving an Order. This Order time and date is stored in the database."

How can I trigger a function to perform something when the time and date in the database is reached?

I am going to use Node JS, Express JS, Mongo DB, React JS for the backend, server, database, and frontend respectively. I am asking for the architecture or creating such trigger of how this can be performed and not for complete code.

Any supporting NPM packages recommendation would be helpful. Thank you.

Note: This is my first application development in any language. I have learnt these technologies only from Udemy courses. The application will have Users select a date in the future and when the future date is reached, the application does some function for them.

like image 761
Sainath A Avatar asked Oct 24 '25 22:10

Sainath A


2 Answers

Create a collection for orders:

 const orders = db.collection("orders");

Then create an index on the due date for faster indexing:

orders.createIndex({ dueDate: 1 });

Now you can start a service to take the lowest date, and check wether that was reached already, otherwise sleep:

const sleep = ms => new Promise(res => setTimeout(res, ms));

(async function() {
  while(true) {  // check forever
    await sleep(2000);
    const cursor = orders.find({ dueDate: { $lte: Date.now() }, processed: false }); // only take those that are done but not yet processed
    while(await cursor.hasNext()) {
      const order = await cursor.next();   
      // process order
      await orders.updateOne(order, { $set: { processed: true }});
    }
  }
})();

Then just add new documents to that collection and watch the magic :)

 orders.insertOne({ processed: false, dueDate: Date.now() + 5000 });
like image 60
Jonas Wilms Avatar answered Oct 27 '25 11:10

Jonas Wilms


You can make use of the following package to achieve your goal: node-schedule

For example:

var schedule = require('node-schedule');
var date = // get date from databse and create a date object for eg: new Date(2012, 11, 21, 5, 30, 0);

var j = schedule.scheduleJob(date, function(){
  console.log('The world is going to end today.');
  // once the job is finished remove the database entry mark it as completed so that it won't run again
});

Note: on the startup, you can also add validation to check the date of your jobs and schedule if the date is in future or invoke the method if it already past and not completed, this is helpful when the application is deployed

like image 21
Piyush Zalani Avatar answered Oct 27 '25 11:10

Piyush Zalani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!