run php script every 5 seconds

11,578

Solution 1

Use Cron job script. Get a 30 seconds interval , you could delay by 5 seconds:

-*/5-22 * * * sleep 5;your_script.php

The above script will run 5am to 10 pm

Another Alternative is,

You need to write a shell script like this that sleeps on the specified interval and schedule that to run every minute in cron:

#!/bin/sh
# Script: delay_cmd
sleep $1
shift
$*

Then schedule that to run in cron with your parameters: delay_cmd 5 mycommand parameters

Solution 2

 #!/bin/sh

 #

 SNOOZE=5

 COMMAND="/usr/bin/php /path/to/your/script.php"

 LOG=/var/log/httpd/script_log.log

 echo `date` "starting..." >> ${LOG} 2>&1

 while true

 do

  ${COMMAND} >> ${LOG} 2>&1

  echo `date` "sleeping..." >> ${LOG} 2>&1

  sleep ${SNOOZE}

 done

The above script will run at a second interval. It will not run the PHP script when it is still processing, also reports the interaction/errors inside a log file.

Share:
11,578
Cyber5h13ld
Author by

Cyber5h13ld

Updated on June 04, 2022

Comments

  • Cyber5h13ld
    Cyber5h13ld almost 2 years

    I know that for running php script every time (seconds or minute) we can use Cron (job or tab) but cron has a 60 sec granularity so we are forced to have an infinite loop for running php script . For example we can write the code below to call it at the top of the script:

    #!/bin/bash
    while [ true ]; do   
       #put php script here
    done
    

    but it's illogical because we must change php execution time in php.ini so we have a lot of problems (Security , overflow , ... ) in server . well, what should we do exactly ? My question is how to run php script every 5 seconds that hasn't got problems in php execution time .