Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Scheduling Jobs on Node.js With node-schedule

DZone's Guide to

Scheduling Jobs on Node.js With node-schedule

Check out this great hands-on tutorial for scheduling jobs in Node. It's perfect if you've ever needed cron-like functionality in this single threaded language.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

Batching is a great part of today's software development. The business world runs on batch from bank statements to promotion emails.

Node.js has some good libraries for such cases.

node-schedule is a light cron-like scheduler for Node.

npm install node-schedule

If your are used to cron and the cron expression format, it will be pretty easy.

var scheduler = require('node-schedule');

var montlyJob = scheduler.scheduleJob('0 0 1 * *', function(){
 console.log('I run the first day of the month');
});

But, there's also a JavaScript object approach:

var scheduler = require('node-schedule');

var rule = new scheduler.RecurrenceRule();
rule.hour = 7
rule.dayOfWeek = new schedule.Range(0,6)

var dailyJob = schedule.scheduleJob(date, function(){
 console.log('I run on days at 7:00');
});

scheduler.scheduleJob(rule,task);

And, you can have tasks submitted by giving a date:

var scheduler = require('node-schedule');

var date = new Date(2017, 1, 1, 0, 0, 0);
var newYearJob = scheduler.scheduleJob(date, function() {
 console.log("Happy new year");
});

However, in the case that your job is not needed you can cancel it pretty easy:

newYearJob.cancel();

Take a look at the Indigo.Design sample applications to learn more about how apps are created with design to code software.

Topics:
cron ,javascript ,node

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}