Search code examples
linuxcronjobs

Using Linux Cron to Run Task every Fortnight


I have a server running Linux operating system. I am trying to schedule a cron job to run a task every two weeks (Fortnight) in Tuesday at 9am. I can only manage to run the task manually by comment (if I don’t want to run the job for this week) and uncomment (if I want to run the job for this week) as following:

0 9 * * 2   root    java -jar test.jar   // will run

# 0 9 * * 2 root    java -jar test.jar   // will not run 

I have attempted to use the following cron job:

0 9 * * 2  case $(($(date +\%s) / (60*60*24*7))) in *[02468]) root  java -jar test.jar 

But this cron script does not seem to work.

Any thought


Solution

  • I would try to execute at 4AM every one of two tuesdays :

    0 4 * * 2 test $((10#$(date +\%W)\%2)) -eq 1 && execute_cmd
    

    We first get week number with date and correct formatting, then the 'one time out of two' thing is done by using 'test' command.

    'test' evaluates to true or false depending on a given expression, here, it evaluates whether $((10#$(date +\%W)\%2)) equals 1 (hence -eq 1), in other words it returns true if the week number is odd.

    So this crontab will execute on odd weeks, on tuesday (2) at 4 AM (0 4).

    More in-depth details here : https://serverfault.com/questions/633264/cronjob-run-every-two-weeks-on-saturday-starting-on-this-saturday