我希望获得一些帮助来为我拥有的三个脚本设置 cron 计划。我需要安排第一个脚本在每月的第一个星期二运行,第二个脚本在每月的第二个星期二运行,第三个脚本在每月的第三个星期二运行。这是我到目前为止所拥有的。
# Run first script on the 1st Tuesday of every month at 9:00 AM
0 9 1,2,3,4,5,6,7 * 2 wget -q -O /dev/null http://site.com/first-script
# Run second script on the 2nd Tuesday of every month at 9:00 AM
0 9 8,9,10,11,12,13,14 * 2 wget -q -O /dev/null http://site.com/second-script
# Run third script on the 3rd Tuesday of every month at 7:00 AM
0 7 15,16,17,18,19,20,21 * 2 wget -q -O /dev/null http://site.com/third-script
Run Code Online (Sandbox Code Playgroud)
我相信这些脚本将在每个月的第 1 个、第 2 个和第 3 个星期二以及该月的 1-21 日运行。从我读到的内容看来,星期几和日期是 AND,是这样吗?
希望这可以通过 cron 实现,否则我将不得不在脚本本身内部决定是否运行脚本。
小智 5
如果您不想将日期检查逻辑直接放入脚本中,则可以在执行脚本之前让 cron job shell 命令部分根据条件检查星期几。
# Run first script on the 1st Tuesday of every month at 9:00 AM
0 9 1-7 * * [ "$(date '+\%a')" = "Tue" ] && wget -q -O /dev/null http://example.com/first-script
# Run second script on the 2nd Tuesday of every month at 9:00 AM
0 9 8-14 * * [ "$(date '+\%a')" = "Tue" ] && wget -q -O /dev/null http://example.com/second-script
# Run third script on the 3rd Tuesday of every month at 7:00 AM
0 7 15-21 * * [ "$(date '+\%a')" = "Tue" ] && wget -q -O /dev/null http://example.com/third-script
Run Code Online (Sandbox Code Playgroud)
如果[ $(date '+\%a')" = "Tue" ]条件成功,则脚本将执行。% 符号必须用反斜杠转义,因为 cron 将 % 视为特殊字符。
因为一周有 7 天,所以每月的第一个星期二保证在 1-7 范围内,第二个星期二在 8-14 范围内,第三个星期二在 15-21 范围内。
要捕获第一个星期二,您不能执行以下操作:
0 9 1-7 * 2 && wget -q -O /dev/null http://example.com/some-script
Run Code Online (Sandbox Code Playgroud)
...因为1-7(月份中的某一天)和2(星期几)实际上将进行OR 运算。由于某种原因,Cron 对待这两个字段的方式与其他字段不同。在上面的示例中,您的脚本最终将在 1-7 范围内每天运行,并且每周二运行。
归档时间: |
|
查看次数: |
7764 次 |
最近记录: |