How to Build a Cron Job with Node js

How to Build a Cron Job with Node js

Build a simple cron scheduler with node.js. This video should get you on your way to automating your task on a computer.

There comes a time in our app development where we will want to automate some certain aspects of our project. Like, run some scripts outside the scope of the project.

Most of the projects I have built for my clients, I built my cron jobs in PHP and used GoDaddy to set up the cron jobs.

In this post we will learn how to set up cron jobs in Node.js applications.

Using setTimeout

setTimeout is the best bet of all Nodejs APIs to use in scheduling execution time of code snippets because it used to defer execution of a function to until a particular time. The setTimeout API takes two parameters:

setTimeout(fn, ms)

The fn parameter is the callback function that is executed when the time ms has elapsed.

The ms is the time in milliseconds that the function must wait before executing the function in the fn param.

Lets see some examples:

setTimeout(()=>console.log("Done !!"), 1000)

We scheduled a function ()=>console.log("Done !!") to execute after the passage of 1 second. Note, we said the time is in milliseconds so passing 1000 milliseconds above is equal to 1 second.

Doing the Math:

1000 miili = 1000 * 10^-3 = 1000
                            ---- = 1
                            1000

So, after 1 second we will see Done !! in our terminal.

Now, let’s create our own cron job using setTimeout API. Note, cron-jobs run after a specified amount of time continuously.

function cron(ms, fn) {
    function cb() {
        clearTimeout(timeout)
        timeout = setTimeout(cb, ms)
        fn()
    }
    let timeout = setTimeout(cb, ms)
}

What did we do above? The cron function takes in the time of the execution and the callback function. First, we setup up the timeout with the setTimeout API passing in the params ms and cb. setTimeout returns a reference to its timeout so we save it in the timeout variable. The function cb we passed to setTimeout is an internal function cb which forms a closure around the ms and fn parameters. The function when called after the ms elapsed, clears the timeout by calling the clearTimeout API passing the timeout variable we saved earlier, then set up another timeout saving the timeout reference to the timeout variable, then last it calls the function fn.

So, now with this our implementation we continuously run the cron without exiting.

Let’s test the cron function:

cron(20000, () => console.log("cron job"))

We will see cron job logged in the terminal after every 2 seconds.

[email protected] MINGW64 /c/wamp/www/developerse/projects/post_prjs/chat-app/server (master)
$ node cron
cron job
cron job
cron job
cron job
cron job
cron job
...
cron job

This will continue to forever until we press Ctrl + C in our terminal.

Now, crons are used in servers, let’s port this our cron function to Express server.

First setup the Node environ and install the Express module

mkdir cron-express
cd node-express
npm init -y
npm install express
touch cron.js

Open cron.js and add the follwoing contents:

// require dependencies
const express = require('express')
const log = console.log
// initialize express and port number
const app = express()
const port = 3000
// configure routes
app.get("/", (req, res) => {
    res.send("index route")
})
// start the server
app.listen(port, () => log(`Server: PORT ${port} active`))

We will edit the function cron to be used as a middleware in Express.

function cron(ms, fn) {
    function cb() {
        clearTimeout(timeout)
        timeout = setTimeout(cb, ms)
        fn()
    }
    let timeout = setTimeout(cb, ms)
    return () => {}
}

We return an empty arrow function in the end so our cron implementation will run immediately on the start of the Express server.

Let’s plug it in in our Express code:

// require dependencies
const express = require('express')
const log = console.log
// initialize express and port number
const app = express()
const port = 3000
// cron function
function cron(ms, fn) {
    function cb() {
        clearTimeout(timeout)
        timeout = setTimeout(cb, ms)
        fn()
    }
    let timeout = setTimeout(cb, ms)
    return () => {}
}
// setup middlewares
cron(20000, () => log("cron job"))
// configure routes
app.get("/", (req, res) => {
    res.send("index route")
})
// start the server
app.listen(port, () => log(`Server: PORT ${port} active`))

Running the server, we will have this:

[email protected] MINGW64 /c/wamp/www/developerse/projects/post_prjs/chat-app/server (master)
$ node cron
Server: PORT 3000 active
cron job
cron job
cron job

Our cron job continuously runs while the server waits for a request.

Using node-cron

We can easily plug-in cron libraries to easily enable us to run crons in Express without writing our custom code. node-cron is one of the best libraries in npm that provides an efficient implementation of cron jobs in Nodejs.

To use node-cron we install it:

npm install node-cron

Import node-cron and schedule a task

const cron = require('node-cron')
cron.schedule("* * * * *",()=> {
    log("logs every minute")
})

This will run every minute. The schedule method is used to schedule a cron and it takes the duration and the function.

Using it in our Express it will look like this:

// require dependencies
const cron = require('node-cron')
const express = require('express')
const log = console.log
// initialize express and port number
const app = express()
const port = 3000
// setup cron job
cron.schedule("* * * * *", () => {
    log("logs every minute")
})
// configure routes
app.get("/", (req, res) => {
    res.send("index route")
})
// start the server
app.listen(port, () => log(`Server: PORT ${port} active`))

Conclusion

We saw how easy it is to set up a cron job in Nodejs and to use it in Express server. We first wrote our own custom cron logic using the setTimeout API, that really opened our eyes on how crons works. They continually run while the other code executes or listens for network requests.

We also, saw how to use the node-cron library to easily set up a cron.

If you have any question regarding this or anything I should add, correct or remove, feel free to comment below. Thanks !!! 🍻

nodejs javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire NodeJs Developer

Looking to build dynamic, extensively featured, and full-fledged web applications? **[Hire NodeJs Developer](https://hourlydeveloper.io/hire-dedicated-node-js-developer/ "Hire NodeJs Developer")** to create a real-time, faster, and scalable...

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Hire Nodejs Developer

Looking to **hire NodeJS Developer**[https://www.dataeximit.com/node-js-development/](https://www.dataeximit.com/node-js-development/ "https://www.dataeximit.com/node-js-development/") to build a perfect back-end to your website or...

What is ECMAScript and How is it Different From JavaScript?

Many times developers use JavaScript and ECMAScript synonymously for each other. Though they are very closely linked to each other, it does not mean they are the same thing.here is a complete story on the history of JavaScript and how it came into existence. To cut the long story short, ECMA in ECMAScript refers to Europen Computer Manufacturers Association to which JavaScript 1.1 was submitted for standardization back in the year 1997.

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.