Run a PHP file every 5 seconds using Shell Script

Solution:

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.


Demonstrating the SECONDS variable

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

Answer

Solution:

The best thing would be to configure crontab to keep the execution or another program installed as a service.

The problem with contrab is that the minimum execution is every 1 minute. Therefore, you should create a script that executes every 5 seconds no more than 12 times. (12 x 5 seconds = 60 seconds)

Kill the process and re-run it with 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

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

Source