运行每月的第2和第4个星期六 [英] Run every 2nd and 4th Saturday of the month
问题描述
在本月的第二个和第四个星期六运行作业的cron(linux)语法是什么?
本月的第二个星期六落在从第8 到到第14 号的日期中的一个(也只有一个)。同样,第四个星期六落在第22个 nd 和第28个之间
的第一个日期。您可能认为您可以使用星期字段将其限制为星期六( 6
在下面一行):
0 1 8-14,22-28 * 6 / path / to / myscript
不幸的是,月份和星期几是一个OR命题, 会导致作业按照
当分钟,小时和分钟时,命令由
cron
月份的字段与当前时间匹配,以及当两个日字段(日期或星期几)中的至少一个与当前时间匹配时。
命令执行的日期可以由两个字段指定:一个月的日期和一周的日期。如果两个字段都受限制(即不是*),则当任一字段与当前时间匹配时,将运行命令。例如,
30 4 1,15 * 5
会导致在每个月1号和15号以及每个星期五上午4:30运行命令。 p>
因此,您需要设置 cron
作业,
cron
条目是:
0 1 8-14,22-28 * * / path / to / myscript
$ p $
然后,在
/ path / to / myscript
,put:#退出除非星期六
if [[$(date +%u)-ne 6]]; then
exit
fi
修改脚本(例如,如果它是一个程序),只需编写一个只包含该检查和对该程序的调用的脚本,然后从
cron
您也可以将星期六的测试放入
crontab
文件本身,地方:0 1 8-14,22-28 * * [`date + \%u` = 6] ;& / path / to / myscript
What's the cron (linux) syntax to have a job run on the 2nd and 4th Saturday of the month?
解决方案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
这篇关于运行每月的第2和第4个星期六的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!