我有一个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?


当前回答

Cron的粒度以分钟为单位,并不是设计为每x秒唤醒一次以运行某项操作。在循环中运行你的重复任务,它应该做你需要的:

#!/bin/env bash
while [ true ]; do
 sleep 30
 # do what you need to here
done

其他回答

在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

使用注意:

$ watch --interval .30 script_to_run_every_30_sec.sh

你可以将脚本作为服务运行,每30秒重新启动一次

注册服务

sudo vim /etc/systemd/system/YOUR_SERVICE_NAME.service

粘贴下面的命令

Description=GIVE_YOUR_SERVICE_A_DESCRIPTION

Wants=network.target
After=syslog.target network-online.target

[Service]
Type=simple
ExecStart=YOUR_COMMAND_HERE
Restart=always
RestartSec=10
KillMode=process

[Install]
WantedBy=multi-user.target

重新加载服务

sudo systemctl daemon-reload

启用服务

sudo systemctl enable YOUR_SERVICE_NAME

启动服务

sudo systemctl start YOUR_SERVICE_NAME

检查您的服务状态

systemctl status YOUR_SERVICE_NAME

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 &

通过反复试验,我找到了正确的表达式:*/30 * * ?* * * 换算成每30秒。 参考:https://www.freeformatter.com/cron-expression-generator-quartz.html 他们提供了每秒运行的表达式:* * * ?* * * */x用于每x个单位运行一次。我在分位和中提琴上试过了。我相信其他人已经发现了这一点,但我想分享我的顿悟时刻!: D