首页 > 解决方案 > 使用 Shell 脚本每 5 秒运行一次 PHP 文件

问题描述

我想使用 Shell 脚本每 5 秒运行一个 php 文件。但有时脚本会每秒运行一次,有时会停止运行。我还需要使用 crontab 吗?请帮忙。

#!/bin/bash
while true; do
    begin=`date +%s`
    php /home/user/www/run.php
    end=`date +%s`
    if [ $(($end - $begin)) -lt 5 ]; then
        sleep $(($begin + 5 - $end))
    fi
done

标签: phpshellsh

解决方案


最好的办法是配置 crontab 以保持执行或其他程序作为服务安装。

conrab 的问题是最低执行时间是每 1 分钟。因此,您应该创建一个每 5 秒执行一次不超过 12 次的脚本。(12 x 5 秒 = 60 秒)

终止该进程并使用 crontab 重新运行它。

例子

sript.sh

#!/bin/bash
# Do not run 12 times because this will same time as next crontab execution
for i in 1 2 3 4 5 6 7 8 9 11 
do 
    php /home/user/www/run.php
    sleep 5
done

在 crontab 上

* * * * * /path/to/script.sh

推荐阅读