Building A CRON-MAN In NodeJs
Tags: node, cron, bot, database
Published: 2019-09-21 15:42:47

---
title: Building A CRON-MAN In NodeJs
published: true
description: 
tags: nodeJs, cron, bot, database
cover_image: https://images.unsplash.com/photo-1569011312883-031325587704?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80
---

In this article we are going to learn how to setup a NodeJs cron-job, our cron 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.


## What is a CRON JOB?

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

![cron-job work flow The Scheduler](https://thepracticaldev.s3.amazonaws.com/i/bdq5g1doqm04mtj5jaab.png)
<figcaption>The Scheduler<figcaption>

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](https://thepracticaldev.s3.amazonaws.com/i/h7mq15klhm1hs0sa7u0j.png)
<figcaption>The cron manager<figcaption>

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

![folder structure](https://thepracticaldev.s3.amazonaws.com/i/u6h0vcmp9ecqvbfgwju3.png)
<figcaption>Your folder structure<figcaption>

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


{% gist https://gist.github.com/phavor/5f0a7df1d0ef99b502c0f908343135f0 %}


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](https://nodejs.org/docs/latest-v10.x/api/timers.html). 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 cron job. 

There is a beautiful article written by [Tendai Mutunhire](https://twitter.com/towersofzeyron) on this. You should check it out: [Events and Timers in Node.js](https://stackabuse.com/how-to-use-timers-and-events-in-node-js/). You can also see the official documentation on [process.nextTick(callback[,…args])](https://nodejs.org/docs/latest-v10.x/api/process.html#process_process_nexttick_callback_args)

Let's continue building, now we will focus on the `actions`. You will notice how we have named our directory `cron-jobs`, this means we can have more than one job and house them together inside of the `cron-jobs` 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.

{% gist https://gist.github.com/phavor/43fefe1e67898187620916725f06a4fd %}


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

Let's now set up the cron manager file, open the `cronMan.js` file and write code away…

{% gist https://gist.github.com/phavor/93f0e583b42fed9c6aa4da08b30988ed %}

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 cron jobs have been called repeatedly](https://thepracticaldev.s3.amazonaws.com/i/0n47tp8y0o15ixd0wsc4.png)
 

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

![you rock](https://thepracticaldev.s3.amazonaws.com/i/2wlhjq7o4rlcij6th288.gif) 
<figcaption>you rock<figcaption>

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