Run every 2nd and 4th Saturday of the month

前端 未结 5 1071
执念已碎
执念已碎 2020-12-16 00:21

What\'s the cron (linux) syntax to have a job run on the 2nd and 4th Saturday of the month?

5条回答
  •  忘掉有多难
    2020-12-16 00:59

    The second Saturday of the month falls on one (and only one) of the dates from the 8th to the 14th inclusive. Likewise, the fourth Saturday falls on one date between the 22nd and the 28th inclusive.

    You may think that you could use the day of week field to limit it to Saturdays (the 6 in the line below):

    0 1 8-14,22-28 * 6 /path/to/myscript
    

    Unfortunately, the day-of-month and day-of-week is an OR proposition where either will cause the job to run, as per the manpage:

    Commands are executed by cron when the minute, hour, and month of year fields match the current time, and when at least one of the two day fields (day of month, or day of week) match the current time.

    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 (i.e., aren't *), 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.

    Hence you need to set up your cron job to run on every one of those days and immediately exit if it's not Saturday.

    The cron entry is thus:

    0 1 8-14,22-28 * * /path/to/myscript
    

    (to run at 1am on each possible day).

    Then, at the top of /path/to/myscript, put:

    # Exit unless Saturday
    if [[ $(date +%u) -ne 6 ]] ; then
        exit
    fi
    

    And, if you can't modify the script (e.g., if it's a program), simply write a script containing only that check and a call to that program, and run that from cron instead.

    You can also put the test for Saturday into the crontab file itself to keep the scheduling data all in one place:

    0 1 8-14,22-28 * * [ `date +\%u` = 6 ] && /path/to/myscript
    

提交回复
热议问题