0

Is it possible to write a cron job that executes every 7 hours without a fixed time of the day? For example, I know I can use this syntax for an execution at 13 and 20h, so 7 hours apart but not rolling:

' * 13-23/7 * * * ', executes at 13h, 20h every day

But what I want is actually:

13h,20h,next day,3h,10h,17h,23h...

is this at all possible with cron? I use the Node.js package node-schedule if this helps.

Thanks, Christian

Cbac
  • 27
  • 4

1 Answers1

0

This should do the job (pardon the pun).. so if you wish to run every X hours, it's kinda awkward in cron expression terms. It's very easy to do something like "run every hour divisible by 7 etc."

But we can use multiple cron expressions to get the same result, e.g.

0 6-20/7 * * 0
0 3-17/7 * * 1
0 0-21/7 * * 2
0 4-18/7 * * 3
0 1-22/7 * * 4
0 5-19/7 * * 5
0 2-23/7 * * 6

And setup 7 separate schedules.. they should combine to give you the sequence you wish.

var schedule = require('node-schedule');

let scheduleList = [
    '0 6-20/7 * * 0',
    '0 3-17/7 * * 1',
    '0 0-21/7 * * 2',
    '0 4-18/7 * * 3',
    '0 1-22/7 * * 4',
    '0 5-19/7 * * 5',
    '0 2-23/7 * * 6'
];

scheduleList.forEach(cron => {
    schedule.scheduleJob(cron, function() {
        console.log('Cron job running!');
    }) 
});

I believe this will give the sequence (for example):

2019-03-17 06:00:00
2019-03-17 13:00:00
2019-03-17 20:00:00
2019-03-18 03:00:00
2019-03-18 10:00:00
2019-03-18 17:00:00
2019-03-19 00:00:00
2019-03-19 07:00:00
2019-03-19 14:00:00
2019-03-20 04:00:00
2019-03-20 11:00:00
2019-03-20 18:00:00
2019-03-21 01:00:00
2019-03-21 08:00:00
2019-03-21 15:00:00
2019-03-21 22:00:00
2019-03-22 05:00:00
2019-03-22 12:00:00
2019-03-22 19:00:00
2019-03-23 02:00:00
2019-03-23 09:00:00
2019-03-23 16:00:00
2019-03-23 23:00:00
2019-03-24 06:00:00

And of course repeating from then.

You could possible use setInterval as well, e.g.

setInterval(() => {
    console.log('setInterval: job running!');
}, 7*60*60*1000);

Though I'm not sure how stable that will be..

Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
  • 1
    I used this to tool to check your example: http://cron.schlitt.info/index.php?cron=0+*%2F7+*+*+*&iterations=10&test=Test It does not look right, it does not roll over, for example the time between 21:00 and 00:00 – Cbac Mar 12 '19 at 09:32
  • Ok, cool, I slightly misunderstood you.. well we could simulate this with multiple cron expressions.. (I'll update the answer). – Terry Lennox Mar 12 '19 at 10:25