Cron Command for twice a month on Sat @12am

5,852

What you want is unfortunately not possible. The schedule “twice a month on saturdays” cannot be expressed using crontab. You can say “twice a month” and you can say “on saturdays” but you cannot link these conditions using AND. They will always be linked using OR. As per man 5 crontab:

Note: The day of a command's execution can be specified by two fields -- day of month, and day of week. If both fields are restricted (ie, are not *), the command will be run when either field matches the current time. For example, ``30 4 1,15 * 5'' would cause a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday.

However, you can use a shell expression to help!

I found this suggestion on a website:

0 0 * * Sun [ $(expr $(date +%W) % 2) -eq 1 ] && /path/to/command

Let‘s disect it!

  • 0 0 * * Sun is the cron schedule. It runs at midnight every sunday.
  • [ $(expr $(date +%W) % 2) -eq 1 ] && /path/to/command is the command (as far as cron is concerned)
    • [ $(expr $(date +%W) % 2) -eq 1 ] successfully returns if the week number of the year is odd
      • expr $(date +%W) % 2 takes the output of date +%W (“week number of year, with Monday as first day of week (00..53)”, other variations are also available) and applies a modulo operation (divide by two, return the remainder)
      • [ $something -eq 1 ] tests whether $something equals 1 and returns the result as its exit code
    • && /path/to/command means to run the command if the previous command was successful (ie. if the week number is odd)

Using this expression, you can keep your scripts unmodified and the decision logic inside the crontab file.

Share:
5,852

Related videos on Youtube

barlop
Author by

barlop

Updated on September 18, 2022

Comments

  • barlop
    barlop over 1 year

    I am wondering if someone can help with the simple but sometimes confusing commands regarding Cron jobs.

    I would like a cron job to run twice a month on a Saturdat @12am.

  • Larssend
    Larssend almost 9 years
    With that entry, the command will be executed every two days each month plus every Saturday.
  • Daniel B
    Daniel B over 2 years
    This won't work as expected. The day columns are linked by OR. This means the command will run every saturday and on the 15th and on the 30th of a month.