如果您想每 n 分钟运行一次 cron,则有几个可能的选项取决于 n 的值。
n 除以 60(1、2、3、4、5、6、10、12、15、20、30)
在这里,通过使用/ 表示法,解决方案很简单:
# 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
m-59/n * * * * command
在上面,n 表示值n,m 表示小于n 或* 的值。这将在分钟m,m+n,m+2n,... 执行命令
n 不整除 60
如果n 不除60,你不能用cron 干净地做到这一点,但这是可能的。为此,您需要在测试检查时间的 cron 中进行测试。这最好在查看 UNIX 时间戳时完成,即自 1970-01-01 00:00:00 UTC 以来的总秒数。假设我们想在 Marty McFly 到达 Riverdale 时第一次开始运行该命令,然后每隔 n 分钟后重复一次。
% date -d '2015-10-21 07:28:00' +%s
1445412480
对于在 `2015-10-21 07:28:00' 之后每 42nd 分钟运行一次 cronjob,crontab 将如下所示:
# 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
* * * * * minutetestcmd "2015-10-21 07:28:00" 42 && command
minutetestcmd 定义为
#!/usr/bin/env bash
starttime=$(date -d "$1" "+%s")
# return UTC time
now=$(date "+%s")
# get the amount of minutes (using integer division to avoid lag)
minutes=$(( (now - starttime) / 60 ))
# set the modulo
modulo=$2
# do the test
(( now >= starttime )) && (( minutes % modulo == 0 ))
备注:UNIX时间不受闰秒影响
备注:cron没有亚秒级精度