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


当前回答

使用fcron (http://fcron.free.fr/) -提供以秒为单位的粒度,比cron (vixie-cron)更好,功能更丰富,也更稳定。我曾经做过一些愚蠢的事情,比如在一台机器上运行60个php脚本,设置非常愚蠢,但它仍然发挥了作用!

其他回答

目前我正在使用下面的方法。工作没有问题。

* * * * * /bin/bash -c ' for i in {1..X}; do YOUR_COMMANDS ; sleep Y ; done '

如果你想每N秒运行一次,那么X = 60/N Y = N。

你可以看看我对这个类似问题的回答

基本上,我在这里包含了一个名为“runEvery.sh”的bash脚本,您可以用cron每1分钟运行一次该脚本,并将希望运行的实际命令和希望运行该命令的频率(以秒为单位)作为参数传递。

就像这样

* * * * ~/bin/ runeveryes.sh 5 myScript.sh

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

你可以将脚本作为服务运行,每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

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.