Home > Net >  Job scheduling in node.js
Job scheduling in node.js

Time:10-20

I want to develop an app which needs to run a scheduled job which writes something to database for every 15 minutes from 9 am to 9 pm How can i implement this? Thanks

CodePudding user response:

Look into this package: https://www.npmjs.com/package/node-cron

Here's an example from their docs:

var cron = require('node-cron');

cron.schedule('*/2 * * * *', () => {
  console.log('running a task every two minutes');
}); 

To write to the database the details vary based on what database you're using exactly. For simplicity you can use Express to connect write to a DB quickly.

Read more here: https://expressjs.com/en/guide/database-integration.html

CodePudding user response:

You can do this.

const CronJob = require("cron").CronJob;

console.log("Before job instantiation");
const job = new CronJob("0 */15 9-21 * * *", function () {
  const d = new Date();
  console.log("Every 15 minutes between 9-21:", d);
});
console.log("After job instantiation");
job.start();
  • Related