Skip to content

Instantly share code, notes, and snippets.

@abhishekr700
Last active January 21, 2018 08:28
Show Gist options
  • Save abhishekr700/abf783a2e17ffdca3626d4ac044d1219 to your computer and use it in GitHub Desktop.
Save abhishekr700/abf783a2e17ffdca3626d4ac044d1219 to your computer and use it in GitHub Desktop.

Scheduling Tasks in Node.JS

With Persistence across server reboots

** If task deadline over while server is off, task will be executed as soon as server starts. ** Stores data in MongoDB..

Module: Mongo-Scheduler-More npmjs.com/package/mongo-scheduler-more

(This is a further developed version of Mongo-Scheduler with more features & updated dependencies.)

Usage : In whichever file you want scheduler.

1.) Basic Steps

//Import module
const Scheduler = require("mongo-scheduler-more");
//Initialize scheduler with connection-stringg & options object
let options = {
    pollInterval: 1000
};`
const scheduler = new Scheduler(`mongodb://${CONFIG.MONGO.HOST}:${CONFIG.MONGO.PORT}/${CONFIG.MONGO.DB_NAME}`, options);

Valid Options
dbname <String> - You can set (and overright) the name of DataBase to use. 
pollInterval <Number> - Frequency in ms that the scheduler should poll the db. Default: 60000 (1 minute).   
doNotFire <bool> - If set to true, this instance will only schedule events, not fire them. Default: false.   

2.) Schedule An Event

scheduler.schedule({
      name: "event-name",
      data: somedatatopassinevent,
      after: item.endDate
 });

** For "after" , pass a Date object only. Do not pass like Date.mow()+2000. Pass like new Date(Date.mow()+2000).

All Fields:
name <String> - Name of event that should be fired
[cron] <String> - A cron string representing a frequency this should fire on
[collection] <Object> - Info about the documents this event corresponds to
[id] <ObjectId> - Value of the _id field of the document this event corresponds to
[after] <Date> - Time that the event should be triggered at, if left blank it will trigger the next time the scheduler polls
[query] <Object> - a MongoDB query expression to select records that this event should be triggered for
[data] <Object|Primitive> - Extra data to attach to the event. Acces via = >  event.data

3.) Add event handlers

scheduler.on("eventname", (err, event) => {
      console.log(event.data);
      //do something here
});

Other Functions :

scheduler.list

List all events.

scheduler.list((err, events) => {
  // Do something with events
})

Error handling

If the scheduler encounters an error it will emit an 'error' event. In this case the handler, will receive two arguments: the Error object, and the event doc (if applicable).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment