Working With Cron Jobs
Slicing 10,000 hours of work to an hour...
What is a cronjob?
A Cron runs jobs for you at specific times
Cron jobs are scheduled tasks, executed on regular time intervals set by the programmer. They work by running preferred scripts. The time intervals for running these scripts are determined by Cron expressions.
A Cron expression is a string consisting of six or seven subexpressions (fields) that describe individual details of the schedule.
Based off what the expression is and what the function was to do, a cron may run every minute, every week or perhaps even annually. There are numerous unique use cases for cron jobs in software consuming large amounts of data.
For instance, a financial website might be programmed to generate backups and email notifications for users and subscribers alike according to their hierarchy. A good example of this sort of provision that you might be used to seeing is how you might have signed up for a free online course. The email server hosting your lectures will start sending you ordered emails based on when you signed up.
This lecturer might have found it very easy sending out 3 emails to 5 students but consider you and as well as 5000 students signed up for the same course over the course of 5 weeks and this lecturer has to send a total of 15 emails to each individual person. What this means is that the course owner has to take note of variables like;
1. Email details, Name, and Date individuals signed up.
2. Type of courses signed up for
With this we will run a job to send emails to individuals on the day they signed up for the next 5 weeks and based on the details of the users send emails for the next 5 weeks. This automation will make the administration of the website way much easier.
There is a simple solution built into javascript. we have things like setTimeout and setInterval to work with however they might be too basic for specific tasks you want to use cron for. However with the Node.js environment we can do more and solve complex problems.
How does Node solve this?
First our entry point is start.js, our cronjob will be in the cron.js ,and finally our package.json for a few Node.js dependencies.
First we add dependencies and put in the value for the port on which we will host our app:
Next is to add the lines of code that listens to the port, initiates the cron method (we will create this in another app)and “starts” the app:
For the cron job in another file.
The ‘module.exports{}’ is for exporting the cronJob function to be used wherever in the app it is required which in this case is the start.js
Now finally for the dependencies which don’t really need much work, you can just use dependencies you need right now. But I will be building a bigger app from and just keep refactoring so I will need all the dependencies here:
You can run the app by doing a node start.js
And that’s about it. More updates on the bigger app as I work on it.