NodeJS: scheduling tasks with Agenda.js
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:
- Scheduled tasks don’t restart when the server goes down.
- Doesn’t work well with Dockerized apps.
- Scheduled tasks success or failure can’t be tracked.
- Uncertainty if schedules will work or not.
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
- Make sure your MongoDB server is running and connect with this:
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.
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:
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:
I hope you use Agenda.js to schedule your tasks, thank you.
Happy Coding!