a blog for those who code

Wednesday 9 September 2015

NodeJS Scheduler

In this post we are going to discuss about modules called cron and agenda which can be used as a NodeJS Scheduler. Cron will allow you to run tasks using Cron Patterns. Agenda is a light weight job scheduling library for Node.js. Lets say you want to schedule a number of tasks at different intervals then you can make use of these modules.

1. Cron

Install : npm install cron

Usage : 

var cron = require('cron');
var cronJob = cron.job('*/10 * * * * *', function() {
  console.log('Runs every 10 seconds ' + new Date())

Available Cron Patterns are - Asterik (*), Ranges (1-5) and Steps (*/10)

2. Agenda - 

Install : npm install agenda

Usage : 

var Agenda = require('agenda');
var agenda = new Agenda({db: {address: 'localhost:27017/agenda-example'}});
agenda.every('*/10 * * * *', 'Run every 10 Seconds ' + new Date());

When you use the above code you might get the error like { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using ppure JS version.

To solve this error you need to copy bson.js file from node_modules\agenda\node_modules\mongodb\node_modules\bson\browser_build\bson.js to node_modules\agenda\node_modules\mongodb\node_modules\bson\build\Release\bson.js. This will solve the above error.

Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment