Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scheduling file every 1 hour using nodejs

Tags:

node.js

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!');
});
like image 239
M.Uma Avatar asked Jan 12 '16 04:01

M.Uma


4 Answers

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

like image 200
BlackMamba Avatar answered Nov 19 '22 03:11

BlackMamba


Why can't you use setInerval()

setInterval(function () {
   console.log('The answer to life, the universe, and everything!');
}, 1 * 60 * 60 * 1000); // 1 hour
like image 36
mestarted Avatar answered Nov 19 '22 04:11

mestarted


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:

  • Every 2 minutes: */2 * * * *
  • Every 2 hours when at 5 minute mark: 5 */2 * * *

You should use this friendly tool to read and verify the config. Example:

enter image description here

It's worth noting that not all cronjob libs support the same fine-grain time level. For example:

  • Linux crontab: at the minute level (allow 5 * in the config)
  • node-schedule: at the second level (allow 6 * in the config)
like image 4
Tho Avatar answered Nov 19 '22 03:11

Tho


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

like image 1
Raja Rajan Avatar answered Nov 19 '22 03:11

Raja Rajan