Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

cron - Run every 2nd and 4th Saturday of the month

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...