How to use the scheduledJobs function in Node.js?
Node Schedule is a versatile task scheduler for Node.js that works both like and unlike cron. With configurable recurrence criteria, it enables you to run scheduledJobs function (arbitrary functions) for execution at particular dates. It doesn’t evaluate forthcoming tasks every second or minute, just using one timer at a time.
Overview
Node Schedule uses time-based scheduling.
Although you can easily bend it to your will, toad-scheduler would be a better option if all you wanted to do was “run this function every 5 minutes.” However, Node Schedule will work better for you if you wish to, for example, “perform this function at the:20 and:50 of every hour on the third Tuesday of every month.” Since the node runtime is now fully supported, Node Schedule also has Windows support in contrast to true cron.
Keep in mind that Node Schedule is made for in-process scheduling, which means that scheduled jobs will only run while your script is still executing, and the schedule will vanish once execution is over. Consider using actual cron if you need to schedule tasks that will execute even if your script is not.
Try agenda or bree if you require persistent jobs that endure restarts and a lock system suitable for multi-node installations.
Installation
You can install using npm.
npm install node-schedule
Jobs and Scheduling
A Job object in Node Schedule serves as a representation of each scheduledJobs function. You have two options: manually construct jobs and then apply a schedule using the schedule() method, or utilize the convenience function scheduleJob() as shown below.
The following events are sent by job objects, which are EventEmitters:
- A run occasion following each execution.
- Every time they are scheduled to operate, a planned event.
- When an invocation is canceled before it is run, an event is triggered.
- Keep in mind that canceled is spelled with a single L in America.
- An error occurs when a schedule-based job invocation throws or returns a rejected Promise.
- A task invocation caused by a schedule that returns successfully or returns a fulfilled Promise is considered successful. In any case, the value returned by the callback or, in the case of a promise, the resolved value, is passed to the successful event.
(A JavaScript date object is received as a parameter by both the scheduled and canceled events.)
Keep in mind that tasks are immediately scheduled for the first time, so if you create a job using the convenience function scheduleJob(), you won’t see the first scheduled event, but you can change the query manually (see below).
Cron-style Scheduling
* * * * * *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ │
│ │ │ │ │ └ day of week (0 – 7) (0 or 7 is Sun)
│ │ │ │ └───── month (1 – 12)
│ │ │ └────────── day of month (1 – 31)
│ │ └─────────────── hour (0 – 23)
│ └──────────────────── minute (0 – 59)
└───────────────────────── second (0 – 59, OPTIONAL
Examples using the cron format include:
const schedule = require('node-schedule'); const job = schedule.scheduleJob('22 * * * *', function(){ console.log('hello world!'); });
run a cron job once the minute has reached 42. (e.g. 19:42, 20:42, etc.).
And:
const job = schedule.scheduleJob('0 17 ? * 0,4-6', function(){ console.log('Today is recognized by Rebecca Black!'); })
Run a cron job every five minutes by entering /5 * * *
For each time the job is invoked, you can also obtain the time that it is scheduled to run:
const job = schedule.scheduleJob('0 2 * * *', function(fireDate){ console.log('This job run at ' + fireDate + ', but actually ran at ' + new Date()); });
This is helpful if you want to save a record of every time a job is invoked for auditing purposes or see if there is a delay in the job invocation when the system is busy.
Incompatible Cron Features
W (the closest weekday) and L (the final day of the month or week) are not supported at this time. The majority of other functions supported by well-known cron implementations ought to operate without issue, including # (nth weekday of the month).
The crontab instructions are parsed using cron-parser.
Date-based Scheduling
Let’s say you very exactly want a function to run on December 21, 2022, at 5:30. 0 represents January in JavaScript, whereas 11 represents December.
const schedule = require('node-schedule'); const date = new Date(2022, 12, 21, 5, 20, 0); const job = schedule.scheduleJob(date, function(){ console.log('Hello World.'); });
You can utilize binding to use recent data in the future:
const schedule = require('node-schedule'); const date = new Date(2012, 12, 25, 5, 23, 0); const x = 'bhanu!'; const job = schedule.scheduleJob(date, function(y){ console.log(y); }.bind(null,x)); x = 'bhanu prasad';
This will record “bhanu!” instead of “bhanu prasad,” which x changes to right away after scheduling, when the planned Job executes.