Home > other >  How to instruct my cron on run job on odd week and even week on every Friday?
How to instruct my cron on run job on odd week and even week on every Friday?

Time:10-05

I have three jobs running on my system with following names

  • "Test1" that runs from Saturday to Thurday

  • "Test2" that runs on even week on every friday

  • "Test3" that runs on odd week on every friday I have figured out on how to schedule from my "Test1" job from Saturday to Thursday like this

    05 11 * * 5-4 This is command to run my test1 job from Saturday to Thursday

But I am not able to figure out on how to schedule my two jobs Test2 and Test3 in such way that Test2 runs on every Friday only when its even week and Test3 to run on every odd week on every Friday only. I will be obliged if someone can provide possible solution to my query

CodePudding user response:

I definitely recommend testing this before using it for something critical, but I think this should work (crafted using crontab.guru).

enter image description here

CodePudding user response:

As there is no field for the week number in the crontab format, it's not possible to schedule a cron to schedule on odd week numbers (or even). The solution needs to execute the cronjob weekly and determine before calling the job if the week is odd or even, this is done below.

First we prepare a cron job to execute every friday of the year at 03:00 (you can select another time :) )

0 3 * * 5 my_weekly_cron

and inside my_weekly_cron (at the beginning) you include the following:

# this will make the job to exit if the week number is even.
[ $(expr $(date ' %W') % 2) = 0 ] && exit

to execute you cronjob in odd numbered weeks.

Or

# this will make the job to exit if the week number is odd.
[ $(expr $(date ' %W') % 2) = 0 ] || exit

to execute your cronjob in even numbered weeks.

You can also do the following (include your test in the crontab entry, so you don't have to touch the cron script itself)

# this will execute the crontab if the week is even
0 3 * * 5 [ $(expr $(date ' %W') % 2) = 0 ] && my_biweekly_cron

will execute my_biweekly_cron in even weeks, while

# this will execute the crontab if the week is odd
0 3 * * 5 [ $(expr $(date ' %W') % 2) = 0 ] || my_biweekly_cron

will execute it in odd weeks.

Explanation

  • [ is the test(1) command. Allows boolean tests in shell scripts. It is used to test if the division of the week number by two results in 0 as remainder.
  • expr(1) allows to calcualte an expresion like checking the result of the week number modulo 2 (modulo operator is % symbol) It calculates the week number and divides it by two, taking the remainder as output.
  • ' %W' is the format string for date(1) command to print the week number only in the date output. This is the source for the week number.
  • Related