DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Legacy App Migration: How Discovery Phase Speeds up Project Delivery
  • MuleSoft: Tactical and Strategical Role of an Application Template
  • Strategies for Cost-Effective On-Demand Delivery App Development
  • The Fundamental Components of Securing a Job as a Software Developer

Trending

  • When RabbitMQ Accepts a Message but Does Not Route It to a Queue
  • Slopsquatting: Building a Scanner That Catches AI-Hallucinated Packages Before They Reach Production
  • Exactly-Once Stream Processing With Apache Flink
  • Choosing a BBD Framework

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Culture and Methodologies
  3. Career Development
  4. Scheduling Jobs on a Sails.js Application

Scheduling Jobs on a Sails.js Application

In one of my projects, there was a need to put scheduled tasks on my Sails.js application. Agenda and node-schedule are my tools of choice when scheduling jobs on a Node.js app, so here, I'll cover how to add scheduling to our Sails.js application using these tools.

By 
Emmanouil Gkatziouras
DZone Core CORE ·
Jun. 22, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
6.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In one of my projects, there was a need to put scheduled tasks on my Sails.js application.

Agenda and node-schedule are my tools of choice when scheduling jobs on a Node.js app. What we will cover is how to add scheduling to our Sails.js application using node-schedule and agenda.

To get started let’s create our application:

sails new SailsScheduling
cd SailsScheduling

My approach to use node-schedule is to add some configuration on the bootstrap.js file.

npm install node-schedule --save

We will add a service to our Sails.js application. Services on a Sails.js application reside on the api/services/path.

Suppose that we implement a service that will send emails:

/**
 * Created by gkatzioura on 6/20/16.
 */

var send = function (text,callback) {

  sails.log.info("Should send text: "+text)
  callback();
};

module.exports =  {
  send: send
}


Then we add our job triggering code on bootstrap.js:

/**
 * Bootstrap
 * (sails.config.bootstrap)
 *
 * An asynchronous bootstrap function that runs before your Sails app gets lifted.
 * This gives you an opportunity to set up your data model, run jobs, or perform some special logic.
 *
 * For more information on bootstrapping your app, check out:
 * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.bootstrap.html
 */
var scheduler = require('node-schedule');

module.exports.bootstrap = function(cb) {

  // It's very important to trigger this callback method when you are finished
  // with the bootstrap!  (otherwise your server will never lift, since it's waiting on the bootstrap)

  var emailService = EmailService;


  var minuteJob  = scheduler.scheduleJob('* * * * *', function(){
    EmailService.send("Random text",function (err, result) {
      sails.log.info("Job executed")
    });
  });

  cb();
};


The next example uses agenda. Instead of rolling out our own configuration, we will use sails-hook-jobs which integrates wonderfully to our sails application as a grunt task.

npm install mongodb@~1.4 --save
npm install sails-hook-jobs --save


We need MongoDB 1.4 version for mongo-skin.

Agenda is backed by MongoDB. Docker users can issue:

docker run --name some-mongo -d mongo

And have a MongoDB server up and running.

The next step is creating the file config/jobs.js containing the configuration.

/**
 * Default jobs configuration
 * (sails.config.jobs)
 *
 * For more information using jobs in your app, check out:
 * https://github.com/vbuzzano/sails-hook-jobs
 */

module.exports.jobs = {

  // Where are jobs files
  "jobsDirectory": "api/jobs",

  // agenda configuration. 
  // for more details about configuration,
  // check https://github.com/rschmukler/agenda
  "db": { 
    "address"    : "localhost:27017/jobs",
    "collection" : "agendaJobs" 
  },
  "name": "process name",
  "processEvery": "10 seconds",
  "maxConcurrency": 20,
  "defaultConcurrency": 5,
  "defaultLockLifetime": 10000
};

The next step is to create the directory jobs on our API folder.
In order to add a job, we should create a JavaScript source file on the API/jobs folder.
Your file should have the ending Job.js. Pay special attention to this, as you do not want to spend hours figuring out what went wrong (like I did).

Our job would send an email every five minutes.

module.exports = function(agenda) {
  var job = {

    frequency: 'every 5 minutes',
    run: function(job, done) {
      EmailService.send("Test email",function (err,result) {

        if(err) {
          sails.log.error("Job was not executed properly");
          done(err);
        } else {
          sails.log.info("Agenda job was executed");
          done();
        }
      });
    },
  };
  return job;
}

There are definitely more tools out there for Sails.js scheduling. My personal choice is agenda, due to its approach to managing your jobs and integrating as a sails task.

You can find the source code on GitHub.

job scheduling application career

Published at DZone with permission of Emmanouil Gkatziouras. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Legacy App Migration: How Discovery Phase Speeds up Project Delivery
  • MuleSoft: Tactical and Strategical Role of an Application Template
  • Strategies for Cost-Effective On-Demand Delivery App Development
  • The Fundamental Components of Securing a Job as a Software Developer

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook