How to create and run cron jobs in Node

You ever want to automate certain tasks on your app, saving you the hustle of doing them manually such as deletion of log files, automated emails or maybe doing a backup of your database data into a MongoDB/SQL dump file, well say no more cron jobs are here to help.

What is a cronjob?

A cron job is a task that automatically runs on a set schedule, example at 0000h you might have a cron job clear site cache on your CDN(Content Delivery Network).

By the end of this tutorial, you should be able to create a simple Node cron job.

We are going to create a simple cron job that deletes a file after a minute. Let's create a file to house our code

$ touch index.js

We need to install certain packages that will ensure we have a cron job

$ npm install express node-cron fs

express: For our cron job to run after a set time we need to initialize a keep-alive connection, which express library will offer when we initialize a HTTP server. You can still use Node inbuilt HTTP library.

Note: We need to have a running program so that our cron job runs, thus the need for a HTTP connection.

node-cron: This is the library that will enable us to run our cron job successfully.

fs: Helps us access the file-system quite well. It comes built-in Node, so there is no need to install it.

Code

The boring but important step is over, now to the good stuff, code. Open index.js with your local editor.