我有一个cron需要每30秒运行一次。

以下是我所拥有的:

*/30 * * * * /bin/bash -l -c 'cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\'''

它能运行,但它是每30分钟或30秒运行一次吗?

此外,我一直在阅读,如果我经常运行cron,它可能不是最好的工具。有没有其他更好的工具,我可以使用或安装在Ubuntu 11.04上,这将是一个更好的选择?有没有办法修复上面的cron?


当前回答

Linux Cron基于时间的调度器默认情况下不会执行间隔小于1分钟的作业。这个配置将向您展示一个简单的技巧,如何使用Cron基于时间的调度器以秒为间隔执行作业。让我们从基础开始。以下cron作业每分钟执行一次:

* * * * * date >> /tmp/cron_test

上述作业将每分钟执行一次,并将当前时间插入到/tmp/cron_test文件中。这很简单!但是,如果我们想每30秒执行一次相同的作业呢?为此,我们使用cron来安排两个完全相同的作业,但是使用sleep命令将第二个作业的执行推迟30秒。例如:

* * * * * date >> /tmp/cron_test
* * * * * sleep 30; date >> /tmp/cron_test

其他回答

Cron作业不能用于以秒为间隔调度作业。例如,你不能安排一个cron作业每5秒运行一次。另一种方法是编写一个使用sleep 5命令的shell脚本。

使用bash while循环每5秒创建一个shell脚本。sh,如下所示。

$ cat every-5-seconds.sh
#!/bin/bash
while true
do
 /home/ramesh/backup.sh
 sleep 5
done

现在,在后台使用nohup执行这个shell脚本,如下所示。这将在退出会话后继续执行脚本。这将每5秒执行一次backup.sh shell脚本。

$ nohup ./every-5-seconds.sh &

在shell循环中运行,示例:

#!/bin/sh    
counter=1
while true ; do
 echo $counter
 counter=$((counter+1))
 if [[ "$counter" -eq 60 ]]; then
  counter=0
 fi
 wget -q http://localhost/tool/heartbeat/ -O - > /dev/null 2>&1 &
 sleep 1
done

Have a look at frequent-cron - it's old but very stable and you can step down to micro-seconds. At this point in time, the only thing that I would say against it is that I'm still trying to work out how to install it outside of init.d but as a native systemd service, but certainly up to Ubuntu 18 it's running just fine still using init.d (distance may vary on latter versions). It has the added advantage (?) of ensuring that it won't spawn another instance of the PHP script unless a prior one has completed, which reduces potential memory leakage issues.

谢谢你的回答。简单来说,我喜欢混合的解决方案,crontab上的控件和脚本上的时间划分。这就是我所做的每20秒运行一个脚本(每分钟3次)。Crontab行:

 * * * * 1-6 ./a/b/checkAgendaScript >> /home/a/b/cronlogs/checkAgenda.log

脚本:

cd /home/a/b/checkAgenda

java -jar checkAgenda.jar
sleep 20
java -jar checkAgenda.jar 
sleep 20
java -jar checkAgenda.jar 

使用注意:

$ watch --interval .30 script_to_run_every_30_sec.sh