每月第n个星期六的Linux crontab [英] Linux crontab for nth Satuday of the month

查看:444
本文介绍了每月第n个星期六的Linux crontab的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了周六,我喜欢在所有工作日进行跑步。
我的crontab条目

I like to run back up for all weekdays except Saturday. My crontab entry

30 16 * * 1,2,3,4,5 ./backup.sh

此条目可以正常工作。
另外,我想在1号,3号星期六休息一下。
如果一个月中有第5个Sutarday,则应运行备份。 crontab的条目将是什么?我猜是

This entry working fine. Also, I like to take back up on 1st, 3rd Saturday. If any 5th Sutarday available in a month then the back up should run. What will be the entry for crontab? I am guessing

30 16 1-7, 15-21, 29-31 * 6 ./backup.sh

我正确吗?

推荐答案


我正确吗?

Am I right?

不,您不正确。 crontab手册指出:

No you are not correct. The crontab manual states:


注意:可以在以下两个字段中指定命令的执行日期。 一个月的一天一个星期的一天。如果两个字段都受限制(即不包含 *字符),则当两个字段中的任何一个与当前时间匹配时,该命令将运行。例如,
30 4 1,15 * 5 会导致命令在每月的1号和15号凌晨4:30运行,星期五。

Note: The day of a command's execution can be specified in the following two fields day of month, and day of week. If both fields are restricted (i.e., do not contain the "*" character), 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.

那我们怎么办呢?

如果要确定是哪个月的星期六,即它是每月的第一个,第二个还是第三个星期六,您要做的就是查看星期六的工作日并执行以下整数计算:

If you want to determine which Saturday of the month it is, i.e. whether it is the 1st, 2nd or 3rd Saturday of the month, all you have to do is look at the weekday of the Saturday and do the following integer computation:

D=$(date "+%d")
echo $(( (D-1)/7 + 1 ))

此值将返回相应的数字。

This value will return the corresponding number. This does not only work for Saturdays but for any Weekday.

由于OP希望cron在第1个,第3个以及可能第5个星期六工作,因此实际上指出: cron在每个奇数周六运行:

Since the OP wants the cron to work on the 1st, 3rd and potentially the 5th Saturday, it actually states that the cron runs on every odd-numbered Saturday:

D=$(date "+%d")
echo $(( ((D-1)/7 + 1) % 2 ))

将此用作另一个测试使我们可以将cron编写为:

Using this as an additional test, allows us to write the cron as:

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *   command to be executed

 30 16  *  *  6   (( (($(date "+\%d") - 1)/7 + 1) % 2 == 1 )) && command

这篇关于每月第n个星期六的Linux crontab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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