【发布时间】:2020-07-03 14:07:27
【问题描述】:
我想安排 cron job 在周一至周五的上午 9:21 至下午 02:30 每 2 分钟运行一次。我怎样才能做到这一点 ?。我知道以下可以从上午 9 点到下午 4 点执行此操作,我该如何修改它以实现上述条件。
提前致谢。
*/2 09-16 * * 1-5 /temp/test_cron.sh >> /temp/test_cron.log
【问题讨论】:
我想安排 cron job 在周一至周五的上午 9:21 至下午 02:30 每 2 分钟运行一次。我怎样才能做到这一点 ?。我知道以下可以从上午 9 点到下午 4 点执行此操作,我该如何修改它以实现上述条件。
提前致谢。
*/2 09-16 * * 1-5 /temp/test_cron.sh >> /temp/test_cron.log
【问题讨论】:
这实际上是正确 cron 表达式的开始。为了得到你要找的东西,你实际上必须结合几个预定的表达式,我相信
我强烈建议使用工具Crontab Guru 来检查您的 crontab 表达式!
# “At every 2nd minute from 21 through 60 past hour 9 on every day-of-week from Monday through Friday.”
21-60/2 9 * * 1-5 /temp/test_cron.sh >> /temp/test_cron.log
# At every 2nd minute past every hour from 10 AM through 1:59 PM on every day-of-week from Monday through Friday.
*/2 10-13 * * 1-5 /temp/test_cron.sh >> /temp/test_cron.log
# At every 2nd minute from 0 through 30 past hour 14 on every day-of-week from Monday through Friday.
0-30/2 14 * * 1-5 /temp/test_cron.sh >> /temp/test_cron.log
另一个可能有帮助的注意事项是检查 cron 邮件(我看到您正在记录,这很棒!)但系统通常也会发送详细说明 cron 作业的 cron 邮件。
这通常位于 /var/spool/mail/{username}
【讨论】:
手册页 (man 5 crontab) 中没有指示任何单行规范都支持您的要求,因为您设置的任何范围都将分别应用于每个时间字段(例如分钟、小时),所以例如,21-30/2 9-14 ... 表示在每个小时后的 21、23、25、27、29 分钟运行。
你当然可以使用多行来达到想要的效果:
21-59/2 9 * * 1-5 /temp/test_cron.sh >> /temp/test_cron.log
1-59/2 10-13 * * 1-5 /temp/test_cron.sh >> /temp/test_cron.log
1-30/2 14 * * 1-5 /temp/test_cron.sh >> /temp/test_cron.log
在这种情况下,间隔是一个小时的一个事实有助于一点,因此至少这三行的中间将确保在 10:01 - 13:59 期间有规律的间隔。如果您有 7 分钟的间隔,那么您将需要更多的行来确保整个过程中的间隔完全有规律。
还要注意手册页中的以下注释:
crontab 语法无法定义所有可能的 可以想象的时期。例如,这并不简单 定义一个月的最后一个工作日。如果一个任务需要在一个 无法在 crontab 语法中定义的特定时间段 最好的方法是让程序本身检查日期 和时间信息,只有在时间段匹配时才继续执行 想要的。
所以您可以采用这种方法并仅使用例如:
1-59/2 9-14 * * 1-5 /temp/test_cron.sh >> /temp/test_cron.log
并在您的 shell 脚本(或者可能是包装脚本)中执行一些测试,例如:
hhmm=`date +%H%M`
if [ $hhmm -lt 0930 -o $hhmm -gt 1430 ]; then exit; fi
(这里我们将 hhmm 视为 4 位十进制数)
【讨论】: