run php script every 5 seconds

ⅰ亾dé卋堺 提交于 2019-12-12 18:26:35

问题


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 .


回答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




回答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.




回答3:


How about using the sleep function to delay every 5 seconds

int sleep ( int $seconds ) - Delays the program execution for the given number of seconds.




回答4:


I prefere to use sleep in your PHP

    while( true ) {

        // function();

        sleep( 5 );

    }

You can stop it after 1 Minute or something like that and restart it with a cronjob. With this solution you are able to execute your script every second after your last executing and it works not asynchronously.

You save ressources with that solution, because php have not to restart all the time...



来源:https://stackoverflow.com/questions/27898231/run-php-script-every-5-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!