Skip to content
Advertisement

Run a PHP file every 5 seconds using Shell Script

I want to run a php file every 5 seconds using Shell Script. But sometimes the script gets run every second or sometimes gets stop running. Do I need to use crontab also? 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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement