NodeJS: scheduling tasks with Agenda.js

Oluwaleke Fakorede hashCode
Hacktive Devs
Published in
2 min readApr 12, 2019

Ever tried to schedule some tasks on your NodeJs app?
Say you wanted to send automated periodic emails to users, or perform some database cleaning at a particular time or at intervals, then you would have probably heard of cron jobs.

Cron is a Linux utility which schedules a command or script on your server to run automatically at a specified time and date. A cron job is the scheduled task itself. Cron jobs can be very useful to automate repetitive tasks.

Scheduling tasks on NodeJs using cron can be done with this cron library.
You can install with:

npm install cron

The basic usage is this:

The ‘* * * * * *’ is the timing of the cron job.
To get your desired schedule or timing, go to https://crontab.guru/.

While cron is good, there are uncertainties, which include:

  1. Scheduled tasks don’t restart when the server goes down.
  2. Doesn’t work well with Dockerized apps.
  3. Scheduled tasks success or failure can’t be tracked.
  4. Uncertainty if schedules will work or not.
urgghhh!!

I bring to you, Agenda!!

Agenda lets you schedule tasks easily without the fear of the above limitations.
Agenda uses a MongoDB database to persist scheduled tasks(and the parameters needed for the task) so that even if the server goes down, the tasks will still run at the specified time or intervals.

Using Agenda:

npm install agenda
  1. Make sure your MongoDB server is running and connect with this:
Connect to Agenda DB

The processEvery parameter is the interval at which agenda checks if there are tasks to be run.

This is an example to send an email to a user.

2. After connecting, we define the task we want to run.
The name is ‘send email report’, the job parameter contains info about the scheduled task/job.

Define agenda jobs

The job.attrs.data is stored in our MongoDB collection so that it can be used to run the jobs.

There are two kinds of jobs:
1. One-time jobs.
2. Periodic jobs.

For one-time jobs:

Create and start a one-time job

For periodic jobs that run at intervals:

Agenda jobs can be scheduled also using cron syntax.

Agenda is easy to use and it is easier to track scheduled jobs and tasks by viewing scheduled, for example:

DB collection view

I hope you use Agenda.js to schedule your tasks, thank you.
Happy Coding!

--

--

Oluwaleke Fakorede hashCode
Hacktive Devs

I love sharing my knowledge in the best way. Software || Data Engineer, mathematician.