简体   繁体   English

使用 Shell 脚本每 5 秒运行一次 PHP 文件

[英]Run a PHP file every 5 seconds using Shell Script

I want to run a php file every 5 seconds using Shell Script.我想使用 Shell 脚本每 5 秒运行一次 php 文件。 But sometimes the script gets run every second or sometimes gets stop running.但有时脚本会每秒运行一次,有时会停止运行。 Do I need to use crontab also?我还需要使用 crontab 吗? Please help.请帮忙。

#!/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

The best thing would be to configure crontab to keep the execution or another program installed as a service.最好的办法是配置 crontab 以保持执行或其他程序作为服务安装。

The problem with contrab is that the minimum execution is every 1 minute. conrab 的问题是最低执行时间是每 1 分钟。 Therefore, you should create a script that executes every 5 seconds no more than 12 times.因此,您应该创建一个每 5 秒执行一次不超过 12 次的脚本。 (12 x 5 seconds = 60 seconds) (12 x 5 秒 = 60 秒)

Kill the process and re-run it with crontab.终止该进程并使用 crontab 重新运行它。

Example例子

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

On crontab在 crontab 上

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

Try this:尝试这个:

#!/bin/bash
while true; do
    sleep 5 &
    php /home/user/www/run.php &
    wait
done

wait (with no arguments) waits for all background jobs to complete, so the loop will block until the longer of the sleep and php processes completes. wait (不带参数)等待所有后台作业完成,因此循环将阻塞,直到睡眠和 php 进程中较长的时间完成。


Demonstrating the SECONDS variable演示SECONDS 变量

rand() { echo $(( RANDOM % $1 )); }

for i in {1..10}; do
    start=$SECONDS
    r=$(rand 10)
    echo "iteration $i, sleeping for $r seconds"
    sleep $r
    end=$SECONDS
    if ((end - start < 5)); then
        n=$((5 - (end - start)))
        echo "sleep for $n seconds"
        sleep $n
    fi
done

# or more simply by assigning to SECONDS
for i in {1..10}; do
    SECONDS=0
    r=$(rand 10)
    echo "iteration $i, sleeping for $r seconds"
    sleep $r
    duration=$SECONDS
    if ((duration < 5)); then
        n=$((5 - duration))
        echo "sleep for $n seconds"
        sleep $n
    fi
done

Certainly more complex than using wait当然比使用wait更复杂

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM