Cron jobs are used to schedule recurring or one-time jobs by a specific time. The libraris allowing these jobs use something known as cron patterns. This is a blog post to quickly and simply explain their usage and functionality.
Tip: Find out the finest granularity of the library function you are using.
The cron job you are using will specify the finest granularity. This can be explained as the least count of the library function.
For example, if it says, 1 minute, the smallest cron job you could run is at the specification of a minute.
So a job that has to be run by specifying the second-th time is not possible.
If the finest granularity is 1 second, you can even run a job at say, at 15 seconds past 4:35 pm.
The best cron library to use is: cron.
Cron Syntax
Assuming the finest granularity is 1 second, a cron pattern has fields.
These fields are:
field allowed values ----- --------------
second 0-59
minute 0-59 hour 0-23 day of month 0-31 month 0-12 (or names, see below) day of week 0-7 (0 or 7 is Sun, or use names)
(source: http://crontab.org/)
They are defined in the below cron function as (*)s:
var job = new CronJob("* * * * * *",
() => console.log('This message displays every second')
)
job.start();
The (*)s are the fields.
Consider these fields as returning boolean values.
Let's say, each field checks the value entered in the function (* in this case) with the current time.
A (*) indicates true for any value.
* * * * * *
sec min hr date mon day
T T T T T T
(T = True)
The cron job checks these all of these fields with the current time of the computer. Only when all of these fields return true, is the function executed.
So this is read as, true for any second, true for any minute, true for any hour, true for any date, and so on.
Running once
Now that you know the syntax, what can you do to make this job run just once?
Let's say I want to run this function only at 06:00 am.
var job = new CronJob("00 00 06 * * *", () =>
console.log("This message displays at 06:00 am")
);
So when the time for hour matches 6, when the time for minute matches 0, and when the time for second matches 0, the function will be executed.
Why the 00 in the first field?
If you remove the 00 from the first field, the function would fire 60 times. That is, for every second at 06:00 am, it would check the syntax, and it will find the cron value matches the current time value. Remember, (*) means true for any value.
So we need it to fire only once, and 00 shall make the function execute at the very first instance the clock strikes 6 am.
Any bugs in the previous code?
Yup, as you can see, the remaining values are set as *. Which means that no matter what date, month or day of the week it is, the function will run.
This will not run just once, it will run everyday. You need to set the exact date, month and day if you need it to run exactly once.
Comments
Post a Comment