我该如何让cron每隔“N”分钟运行一次,其中n%5 == 1?

我知道我可以在cron中每五分钟运行一行,如下所示:

*/5 * * * * /my/script 

如果我不想让它在12:00,12:05,12:10运行,而是在12:01,12:06,12:11等运行? 我想我可以这样做:

  1,6,11,16,21,26,31,36,41,46,51,56 * * * * /my/script 

…但这是丑陋的 有没有更好的方法来做到这一点?

 1-56/5 * * * * /my/script 

这应该在vixiecron上工作,我不知道其他的实现。

使用你的第一个时间表

 */5 * * * * /my/script 

并将其添加到您的脚本的开始:

 sleep 60 

(是的,这是一个笑话)

这是一个相当古老的话题,但是时间已经过去了,现在还有其他一些select。 其中之一是不要使用cron,并使用systemd定时器。 使用这些可以提供比秒级更高的粒度以及许多其他选项

更多信息可以在这里findhttps://wiki.archlinux.org/index.php/Systemd/Timers

例如运行一个adhoc命令

 # systemd-run --on-calendar="*:1/5" /bin/touch /tmp/foo2 Running timer as unit run-r31335c4878f24f90b02c8ebed319ca60.timer. Will run service as unit run-r31335c4878f24f90b02c8ebed319ca60.service. # systemctl status run-r31335c4878f24f90b02c8ebed319ca60.timer ● run-r31335c4878f24f90b02c8ebed319ca60.timer - /bin/touch /tmp/foo2 Loaded: loaded Transient: yes Drop-In: /run/systemd/system/run-r31335c4878f24f90b02c8ebed319ca60.timer.d └─50-Description.conf, 50-OnCalendar.conf, 50-RemainAfterElapse.conf Active: active (waiting) since Wed 2017-10-25 09:05:13 UTC; 40s ago # ls -l /tmp/foo* -rw-r--r-- 1 root root 0 Oct 25 09:06 /tmp/foo2 # sleep 300; ls -l /tmp/foo* -rw-r--r-- 1 root root 0 Oct 25 09:11 /tmp/foo2 # date; ls -l /tmp/foo2 Wed Oct 25 09:21:42 UTC 2017 -rw-r--r-- 1 root root 0 Oct 25 09:21 /tmp/foo2 

编辑:这些types的定时器不会持续重启,如果你想让他们确保生成一个合适的服务文件,相关的oncalendar行

我会创build一个新的脚本“延迟启动”,将睡眠时间作为第一个参数,脚本作为其余的运行。 我会让脚本检查脚本的行crontab行,只有当行没有被注释掉时才启动脚本。 这使得它可重用,并且ps不会报告脚本运行时,它实际上不是。

 #!/bin/bash sleeptime=$1 sleep ${sleeptime} shift if ( ! crontab -l | grep -e '#.+delaystart '${sleeptime} $* ) then $* fi 

sean.bright的笑话让我想到了……为什么不使用…

 * * * * * /my/script 

…在脚本内部做这个…

 #!/bin/bash export WHEN=`date '+%M'` echo $WHEN export DOIT=`echo "$WHEN % 5" | bc` echo $DOIT if [ $DOIT != 0 ] ; then echo "ha ha ha" fi echo "done" 

… …一个kludge …也许,但像crontab丑陋…我不知道。