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.
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.
Admin@PHILIPSZDAVIDO 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:
Admin@PHILIPSZDAVIDO 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.
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`))
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