In this article we are going to learn how to setup a NodeJs cronjob, our cronjob will lookup our database collection and delete redundant users. We are going to see a few NodeJs APIs that will help us achieve our desired goal. There’s a lot to learn and I can’t wait to jump right in.

Let’s jump right in

What is a CRONJOB?

A cronjob is a program that runs regularly at a specified time, and carries out any specified task. You may think of it as a bot. You could want to send out newsletters to all who signed up on your platform today, you could want to check another service which your application uses for updates and then correctly update your own service. You could do just about anything with a cronjob.

Okay, I hear you, why do I need a CRONJOB?

You see, while working with a database, you may notice that users of your application often upload or save files which they do not need into your database or cloud storage bucket. Your cronjob would occasionally check your storage system, find these redundant files and implement your desired instructions. You are not limited to the database anyway, you can implement this just about anywhere, ideally, the storage system is a popular use case.

The cron-man or manager will handle all our cronjobs. This means all our cronjobs will be managed from the same file.

Ready?

Now let’s get started

I will assume you already have a functional View and Model already, so we can get to the cron manager immediately.

We will structure our cronjob runner into 3 parts:

The Scheduler

The Action

The cron-man

cronjob work flow

The Scheduler

The scheduler will take in 2 parameters, the time interval in milliseconds and the action to run.

The Action

This is a function which will be called by our scheduler, this function bears the logic of what needs to be done every time our scheduler calls it. It is important to make your actions pure. Using pure functions will help check against memory leaks and side-effects.

The Cron-Man

The cron manager will bootstrap all our schedulers and manage them for us. We simply import our scheduler function and actions here. This is important for debugging and more so it makes our cron modular.

The cron manager

Now that we have conceptually described our cron program, let’s get into the code level. Create a cron-man directory in your project, it should have 2 sub folders (cron-jobs & scheduler) and the cronMan.js file.

your folder structure

We start by fleshing out the scheduler function. It will look like so:

Our scheduler needs two vital pieces. The setInterval() timer API and the process.nextTick() API from NodeJs. For more information on the timer API, see their documentation. The setInterval() takes the time and the action to call once the time provided has elapsed.

The process.nextTick() will ensure that our scheduler function is called once the current job in the NodeJs event loop is completed. It gets called before any other I/O event, or timers are loaded into the event loop. This is a good way for us to hook into the life-cycle of our program and inject our cronjob.

There is a beautiful article written by Tendai Mutunhire on this. You should check it out: Events and Timers in Node.js. You can also see the official documentation on process.nextTick(callback[,…args])

almost there

Let’s continue building, now we will focus on the actions. You will notice how we have named our directory cronjobs, this means we can have more than one job and house them together inside of the cronjobs directory. For this example, we will setup a deleteInactives cronjob. This will lookup our database and delete all currently inactive users.

In a real-world application, you should not delete the users, but the redundant files they have, like pictures, videos, pdfs, and the likes which have not been saved by the user but uploaded to your database.

In our example app, say we give all users 24 hours to activate their accounts, at the expiration of this time, we will delete all inactive accounts. Great, let’s write the code now.

Our deleteInactive users function above will remove any user whose isActive property is false .

Let’s now setup the cron manager file, open the cronMan.js file and write code away…

All we have to do now is to inject the cronMan.js file into our app. Inside our index.js , we will require the cronMan file at line 1 like so:

require("./cron-man/cronMan");

Awesome, now when check our console we should see new messages logging the number of users deleted.

our results after the cronjobs have been called repeatedly

Currently, our scheduled job runs every 10000 milliseconds, you should set your timer according to the needs of your application.

you rock…

There you have it. You have successfully setup your first CRONJOB. That was easy right? Now go and save the world your cron-man 🚀🚀🚀