DEV Community

Richard Wynn
Richard Wynn

Posted on

3 Task Scheduling Packages for Node.js

⏳ Task scheduling allows you to schedule your code to be executed at a scheduled date/ time, at recurring intervals, or once after a specified interval. In Linux, this is often handled by packages like cron. In this article, I will show you top 4 task scheduling packages that emulate cron-like functionality for Node.js apps.

Node Cron

The node-cron module is tiny task scheduler in pure JavaScript for node.js based on GNU crontab. This module allows you to schedule task in node.js using full crontab syntax.

Popularity

  • 1.449.775 Weekly Downloads (Up to the time of this article)

Installation

You can install node-cron by using npm.

$ npm install --save node-cron
Enter fullscreen mode Exit fullscreen mode

Examples

var cron = require('node-cron');

cron.schedule('* * * * *', () => {
  console.log('running a task every minute');
});
Enter fullscreen mode Exit fullscreen mode

Node Schedule

Node Schedule is a flexible cron-like and not-cron-like job scheduler for Node.js. It allows you to schedule jobs (arbitrary functions) for execution at specific dates, with optional recurrence rules. It only uses a single timer at any given time (rather than reevaluating upcoming jobs every second/ minute).

Popularity

  • 1.941.398 Weekly Downloads (Up to the time of this article)

Installation

You can install node-schedule by using npm.

$ npm install node-schedule
Enter fullscreen mode Exit fullscreen mode

Examples

const schedule = require('node-schedule');

const job = schedule.scheduleJob('42 * * * *', function(){
  console.log('The answer to life, the universe, and everything!');
});
Enter fullscreen mode Exit fullscreen mode

Agenda

Agenda is a light-weight job scheduling library for Node.js that offers:

  • Minimal overhead. Agenda aims to keep its code base small.
  • Mongo backed persistence layer.
  • Promises based API.
  • Scheduling with configurable priority, concurrency, and repeating.
  • Scheduling via cron or human readable syntax.
  • Event backed job queue that you can hook into.

Popularity

  • 55.774 Weekly Downloads (Up to the time of this article)

Installation

npm

You can install agenda by using npm.

$ npm install agenda
Enter fullscreen mode Exit fullscreen mode

You will also need a working Mongo database (v3) to point it to.

CJS / Module Imports

For regular javascript code, just use the default entrypoint

const Agenda = require('agenda');
Enter fullscreen mode Exit fullscreen mode

For Typescript, Webpack or other module imports, use agenda/es entrypoint:

import { Agenda } from 'agenda/es';
Enter fullscreen mode Exit fullscreen mode

NOTE:

  • If you're migrating from @types/agenda you also should change imports to agenda/es.
  • Instead of import Agenda from 'agenda' use import Agenda from 'agenda/es'.

Examples

const mongoConnectionString = "mongodb://127.0.0.1/agenda";

const agenda = new Agenda({ db: { address: mongoConnectionString } });

// Or override the default collection name:
// const agenda = new Agenda({db: {address: mongoConnectionString, collection: 'jobCollectionName'}});

// or pass additional connection options:
// const agenda = new Agenda({db: {address: mongoConnectionString, collection: 'jobCollectionName', options: {ssl: true}}});

// or pass in an existing mongodb-native MongoClient instance
// const agenda = new Agenda({mongo: myMongoClient});

agenda.define("delete old users", async (job) => {
  await User.remove({ lastLogIn: { $lt: twoDaysAgo } });
});

(async function () {
  // IIFE to give access to async/await
  await agenda.start();

  await agenda.every("3 minutes", "delete old users");

  // Alternatively, you could also do:
  await agenda.every("*/3 * * * *", "delete old users");
})();
Enter fullscreen mode Exit fullscreen mode
agenda.define(
  "send email report",
  { priority: "high", concurrency: 10 },
  async (job) => {
    const { to } = job.attrs.data;
    await emailClient.send({
      to,
      from: "example@example.com",
      subject: "Email Report",
      body: "...",
    });
  }
);

(async function () {
  await agenda.start();
  await agenda.schedule("in 20 minutes", "send email report", {
    to: "admin@example.com",
  });
})();
Enter fullscreen mode Exit fullscreen mode
(async function () {
  const weeklyReport = agenda.create("send email report", {
    to: "example@example.com",
  });
  await agenda.start();
  await weeklyReport.repeatEvery("1 week").save();
})();
Enter fullscreen mode Exit fullscreen mode

👋 And you? Have you ever used any of these packages or another packages to do cron stuff in Node.js? Feel free to put a comment below 😃

📱 Keep in Touch
If you like this article, don't forget to follow and stay in touch with my latest ones in the future by following me via:

Twitter: https://twitter.com/RichardWynn01
Medium: https://richard-wynn.medium.com
Github: https://github.com/richard-wynn

Top comments (0)