如何让unix脚本每15秒运行一次?

Nic*_*ant 83 unix cron command sleep

我已经看到了一些解决方案,包括监视和在后台运行循环(和休眠)脚本,但没有什么是理想的.

我有一个需要每15秒运行一次的脚本,而且由于cron不会支持秒数,所以我只想搞清楚其他事情.

在unix上每15秒运行一个脚本最强大,最有效的方法是什么?脚本还需要在重新启动后运行.

ras*_*ani 285

如果你坚持从cron运行你的脚本:

* * * * * /foo/bar/your_script
* * * * * sleep 15; /foo/bar/your_script
* * * * * sleep 30; /foo/bar/your_script
* * * * * sleep 45; /foo/bar/your_script
Run Code Online (Sandbox Code Playgroud)

并将您的脚本名称和路径替换为/ foo/bar/your_script

  • 这非常聪明.+1 (18认同)
  • 我感到很尴尬,我不得不谷歌这个解决方案.也许stackoverflow让我少思考. (18认同)
  • 这对我很有用.使用后台任务在此之上的解决方案产生了几个子进程并导致我的内存问题. (4认同)
  • 如果运行php脚本执行此操作:`*****sleep 15; php/foo/bar/your_script` (2认同)
  • 如果运行 php 脚本,您可以在 php 脚本的顶部添加一行 `#!/usr/bin/php` 并使其可执行 (2认同)

Ric*_*dle 75

我会每分钟使用cron运行一个脚本,并使该脚本运行您的脚本四次,运行之间的休眠时间为15秒.

(这假设您的脚本可以快速运行 - 如果没有,您可以调整睡眠时间.)

这样,您可以获得cron15秒运行期间的所有好处.

编辑:另见@ bmb的评论如下.

  • 如果脚本运行所需的时间不一致,请制作脚本的四个副本.一个人在开始前睡15秒,另一个30,另一个45,另一个零.然后每分钟运行四个. (55认同)

Mar*_*kel 15

以上修改版:

mkdir /etc/cron.15sec
mkdir /etc/cron.minute
mkdir /etc/cron.5minute
Run Code Online (Sandbox Code Playgroud)

添加到/ etc/crontab:

* * * * * root run-parts /etc/cron.15sec > /dev/null 2> /dev/null
* * * * * root sleep 15; run-parts /etc/cron.15sec > /dev/null 2> /dev/null
* * * * * root sleep 30; run-parts /etc/cron.15sec > /dev/null 2> /dev/null
* * * * * root sleep 45; run-parts /etc/cron.15sec > /dev/null 2> /dev/null

* * * * * root run-parts /etc/cron.minute > /dev/null 2> /dev/null
*/5 * * * * root run-parts /etc/cron.5minute > /dev/null 2> /dev/null
Run Code Online (Sandbox Code Playgroud)


scv*_*lex 13

不会在后台运行这个吗?

#!/bin/sh
while [ 1 ]; do
    echo "Hell yeah!" &
    sleep 15
done
Run Code Online (Sandbox Code Playgroud)

这几乎和它一样高效.重要部分仅每15秒执行一次,脚本会在其余时间休眠(因此不会浪费周期).

  • 编辑必须至少8个字符(这是愚蠢的,恕我直言)所以我不能在第3行的末尾添加`&`.无论如何,这不会每15秒运行一次.这运行每"15秒+无论多长`echo hello`运行".这可能是0.01秒; 可能是19个小时. (7认同)