Cron Jobs
Cron Jobs allows developers to automate tasks in their applications.
What are Cron Jobs?
Cron jobs are scheduled jobs which can be executed repeatedly at a particular interval of time. The most common use case of these jobs is to automate tasks so that the developer does not have to waste their time in order to wait for a specific time to complete a task. A script can be written and that script will be executed automatically according to the time entered by the developer.
Some examples:
- Sending users email reminding them to take backup of their data on Sunday of every week.
- Sending messages to the users 10 minutes before every scheduled meeting.
Understanding how to write cron jobs
This is how time is specified by the developer. This is called the cron expression. The asterisks represents different units of time. The first asterisk represents seconds which are optional to be specified and can be skipped. The second asterisk represents the minutes which are mandatory to be added. The value of minutes can be from 0 - 59. The third asterisk represents the hour which is also mandatory. The value of hours is from 0 - 24. The fourth asterisk represents the day of month which is also mandatory. The value for day of month is between 1 - 31. The fifth asterisk represents the month which is also mandatory. The value of month is from 1 - 12 or names can also be mentioned. The sixth asterisk represents the day of the week which is also mandatory. The value for day of week is from 0 - 6 or names can also mentioned.
Example: ('25 20 * * *') this will be executed at 8:25 pm everyday.
Using cron jobs in code
Cron jobs can be executed in different programming languages but in this example Node.js will be used.
Make sure node.js is installed on the computer.
node --version
will make sure that right version of node is installed.
Run the command node init --y
to initialise a project.
Create a file index.js where example code will be written.
The project structure will look something like
Move into the created directory and installed the packages as:
npm i express node-cron@3.0.0
These packages will be added as dependencies in the package.json file
{
"name": "cronexample",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.1",
"node-cron": "^3.0.0"
}
}
Writing code in the index.js file
const express = require('express');
const cron = require('node-cron');
const app = express();
cron.schedule('26 16 * * *', () => {
console.log('Scheduled to be logged at 4:26 PM');
})
app.listen(8000, () => console.log('Server is running on port 8000'))
Output:
So this script will executing everyday at 4:26 PM.
cron.schedule(expression, function, options)
expression: It is the cron expression in which the developer specifies the specific time.
function: It is the lines of code which will get executed at that time.
options: It is an optional object of configurations for scheduling the job. It takes two properties which are scheduled and timezone.
cron.schedule('* * * * *', () => {
console.log('Scheduled to be executed every minute');
}, {
scheduled: true,
timezone: "Asia/Kolkata"
})
This method will be executed every minute.
cron.start()
const job = cron.schedule('* * * * *', () => {
console.log('Scheduled to be executed every minute');
}, {
scheduled: false,
})
job.start()
This method will not start until the invoked with the start method.
cron.stop()
const job = cron.schedule('* * * * *', () => {
console.log('Scheduled to be executed every minute');
})
job.stop()
This job will keep on executing every minute until stopped by the stop method.
Entering values in cron expression dynamically
const min = '54'
const hr = '19'
const dayOfMonth = 30
const month = 'July'
cron.schedule(`${min} ${hr} ${dayOfMonth} ${month} *`, () => {
console.log(`Cron job executed on time: ${hr}:${min} and date: ${dayOfMonth} / ${month} `)
})
In this way value from client can also be taken and cron jobs will run according to that.
Output:
Conclusion
Cron Jobs can be used with different frameworks like Spring Boot, Django etc. as well which makes it subtle for the developer to automate tasks and focus more on the logic of the application.
#BlogsWithCC on Hashnode