Dennis Nedry
Dennis Nedry

Reputation: 4777

Execute different nodejs scripts at a given time

I am looking for a good solution on fire different javascript files with nodejs at a given time on a Server running on Ubuntu.

I have about 10 different scripts and each should be fired 15 times a day! My first approach was to use at but this gets really messy with that much events.

Now I thought about using Node-Schedule what some of you guys here on SO suggested but I'm not sure if that's the best solution for my task ...

If Node-Schedule should still be the best approach - what structure would you use?

var schedule = require('node-schedule');
var d1 = new Date(2015, 10, 20, 18, 55, 0);
var d2 = new Date(2015, 10, 20, 18, 58, 0);

var xd1 = schedule.scheduleJob(d1, function(){
    test.js;
});

var xd2 = schedule.scheduleJob(d2, function(){
    test.js;
});

Doesn't seems that DRY ... ;)

Upvotes: 1

Views: 1457

Answers (2)

Christian Pekeler
Christian Pekeler

Reputation: 1070

I wouldn't create a node program just to schedule another node program. Use plain cron.

If you can run your job 16 times a day instead of 15 times, it would be every 90 minutes which you can schedule with these two cron expressions:

' 0 0/3 * * * node test.js'
'30 1/3 * * * node test.js'

If it has to be 15 times, this schedule has pretty good distribution (at most once an hour, at least every other hour, 15 times per day):

'0 0/2,1,9,17 * * * node test.js'

Any difficulty understanding this schedule, use this site. If you need your 15 invocations to be spaces equally (every 96 minutes), I'm afraid you'd need to break them into 5 schedules:

 0 0,8,16  * * * node test.js
36 1,9,17  * * * node test.js
12 3,11,19 * * * node test.js
48 4,12,20 * * * node test.js
24 6,14,22 * * * node test.js

Upvotes: 1

PatrickD
PatrickD

Reputation: 1156

If you need to run your scripts on a daily basis, this date based scheduling is not the best solution. The cron style scheduling is a better fit.

For example

var xd1 = schedule.scheduleJob('0 * * * *', function(){
    test.js;
});

will run your function every hour (0:00, 1:00, 2:00 and so on = 24 times a day).

And

var xd1 = schedule.scheduleJob('0 */2 * * *', function(){
    test.js;
});

will run your function every two hours (0:00, 2:00, 4:00 and so on = 12 times a day).

Is the 15 times a day a hard requirement? You can't define this kind of interval very easy with the cron syntax, without splitting it up into different cronjobs (= define more job with the same function call).

This example would run 15 times a day, but it is not balanced throughout the day:

var xd1 = schedule.scheduleJob('*/25 */5 * * *', function(){
    test.js;
});

Upvotes: 1

Related Questions