Scheduling jobs on Node.js with agenda

There are many ways to schedule jobs in your application. A very common practice is to back our jobs with persistence.
By doing so we will be informed in the future if the job did fail or succeed and when it should be the next execution.

Agenda is a light-weight job scheduling library for node.js. It is backed with mongodb.

It is really simple to get started. The first thing we have to do is to configure the mongodb database connection sting.

var Agenda = require('agenda');

var connectionString = "";
var agenda = new Agenda({db: { address: connectionString, collection: 'jobs' }});

Next step would be to specify jobs.

Suppose we have an EmailService like this

EmailService = {
            console.log("sending email");

Then we shall define a job

agenda.define('send email', function(job, done) {
    EmailService.send(function(err,result) {
        if(err) {
        } else {

We just defined a job with agenda in a human way.

agenda.on('ready',function() {
 agenda.every('1 day','send email'); 

Once we defined the jobs we need to set the time interval that the agenda instance will look up for new jobs.

agenda.processEvery('1 minute');

By querying to our mongodb database we are able to receive our job status.

{ "_id" : ObjectId("5767110c779be08d4e1b3109"), "name" : "send email", "type" : "single", "data" : null, "priority" : 0, "repeatInterval" : "1 day", "repeatTimezone" : null, "lastModifiedBy" : null, "nextRunAt" : ISODate("2016-06-20T21:39:24.931Z"), "lockedAt" : null, "lastRunAt" : ISODate("2016-06-19T21:39:24.931Z"), "lastFinishedAt" : ISODate("2016-06-19T21:39:24.932Z") }

Agenda is pretty featureful.
For example you can use it with cron format too.

For example running our job every minute

agenda.on('ready',function() {
 agenda.every('* * * * *','send email');

Other cool features is retrieving jobs in a mongodb query format and modifying them.{name: 'send email'}, function(err, jobs) {

Last but not least agenda-ui is a great tool for visualizing agenda jobs.

Overall agenda is my personal favorite when it comes to adding josb to my node.js application.
It is backed by mongodb and easy to configure.
I believe that one of its main strengths is giving you good control over your jobs.


3 thoughts on “Scheduling jobs on Node.js with agenda

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.