Cron Job仅在一周的特定日期运行几天 [英] Cron Job to run on a range of days only on a particular day of week

查看:718
本文介绍了Cron Job仅在一周的特定日期运行几天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

0 0 2-31 * sun         /home/ubuntu/x.h
0 0 2-31 * mon-sat     /home/ubuntu/y.h

这最终会同时运行它们。我在这里做错了吗?

This ends up running both of them. Am I doing something wrong here?

推荐答案

这是crontab格式:

This is the crontab format:

* * * * *
| | | | |
| | | | +---- Day of the Week   (range: 0-6, 0 standing for Sunday)
| | | +------ Month of the Year (range: 1-12)
| | +-------- Day of the Month  (range: 1-31)
| +---------- Hour              (range: 0-23)
+------------ Minute            (range: 0-59)

Ubuntu man 5 crontab 说:

  field          allowed values
  -----          --------------
  minute         0-59
  hour           0-23
  day of month   1-31
  month          1-12 (or names, see below)
  day of week    0-7 (0 or 7 is Sun, or use names)

因此,这应该对您有用:

So, this should work for you:

0 0 2-31 * 0         /home/ubuntu/x.h
0 0 2-31 * 1-6       /home/ubuntu/y.h

我不确定为什么在周六运行7-您的系统时间是否正确且在正确的时区?

I'm not sure why 7 would run on Saturday--is your system time accurate and in the right timezone?

编辑:嗯,是的,很遗憾,您不能同时指定星期几和每月几号。从 man 5 crontab 开始:

Edit: Ah, yes, unfortunately you cannot specify both the day of the week and the day of the month. From man 5 crontab:


注意:命令的执行日期可以是由两个字段指定-每月的日期和星期几。如果两个字段都受限制(即不是*),则当任一字段与当前时间匹配时,将运行该命令。例如, 30 4 1,15 * 5会导致命令在每月的1号和15号的凌晨4:30以及每个星期五运行。但是,可以通过在命令中添加测试来获得所需的结果(请参见下面的示例CRON文件中的最后一个示例)。

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 (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. One can, however, achieve the desired result by adding a test to the command (see the last example in EXAMPLE CRON FILE below).

因此,答案是:

0 0 2-31 * *       test $(date +\%u) -eq 7 && /home/ubuntu/x.h
0 0 2-31 * *       test $(date +\%u) -ne 7 && /home/ubuntu/y.h

$(date'+%u') 返回1-7,代表星期一至星期日。以 echo $(date'+%u')为例。

$(date '+%u') returns 1-7 representing Monday thru Sunday. Try echo $(date '+%u') for an example.

这篇关于Cron Job仅在一周的特定日期运行几天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆