I want to run a print statement every 1 hour in Windows environment using node.js. I use the package node-schedule.
But when I tried running this, the output is not as expected. I think my schedule format is wrong.
So I tried the following code:
var schedule = require('node-schedule');
var j = schedule.scheduleJob('*/1 * * *', function(){
console.log('The answer to life, the universe, and everything!');
});
var schedule = require('node-schedule');
var j = schedule.scheduleJob('* 1 * * *', function(){ // this for one hour
console.log('The answer to life, the universe, and everything!');
});
The cron format consists of:
* * * * * * ┬ ┬ ┬ ┬ ┬ ┬ │ │ │ │ │ | │ │ │ │ │ └ 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)
Here is the link: https://github.com/node-schedule/node-schedule
Why can't you use setInerval()
setInterval(function () {
console.log('The answer to life, the universe, and everything!');
}, 1 * 60 * 60 * 1000); // 1 hour
You can try this:
const schedule = require('node-schedule');
const job = schedule.scheduleJob('1 * * * *', () => { // run every hour at minute 1
console.log('The answer to life, the universe, and everything!');
});
More examples:
*/2 * * * *
5 */2 * * *
You should use this friendly tool to read and verify the config. Example:
It's worth noting that not all cronjob libs support the same fine-grain time level. For example:
This will run every 1 hour, 0th minute, 0th second( ex: execute at 1PM, 2PM, 3PM etc):
var CronJob = require('cron').CronJob;
var job = new CronJob('0 0 */1 * * *', function() {
console.log('The answer to life, the universe, and everything!');
});
job.start();
Refer: https://www.npmjs.com/package/cron
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With