简体   繁体   English

每5秒运行一次php脚本

[英]run php script every 5 seconds

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 . 我知道每次运行php脚本(秒或分钟)时,我们都可以使用Cron(作业或制表符),但是cron具有60秒的粒度,因此我们被迫有一个无限循环来运行php脚本。 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 . 但这是不合逻辑的,因为我们必须更改php.ini中的php执行时间,因此服务器中存在很多问题(安全性,溢出等)。 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 . 我的问题是如何每5秒运行php脚本,而php执行时间没有问题。

Use Cron job script. 使用Cron作业脚本。 Get a 30 seconds interval , you could delay by 5 seconds: 间隔30秒,您可以延迟5秒:

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

The above script will run 5am to 10 pm 上面的脚本将在凌晨5点至晚上10点运行

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 然后计划使用您的参数在cron中运行它:delay_cmd 5 mycommand参数

 #!/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. 仍在处理时,它将不会运行PHP脚本,还会在日志文件中报告交互/错误。

How about using the sleep function to delay every 5 seconds 如何使用睡眠功能每5秒延迟一次

int sleep ( int $seconds ) - Delays the program execution for the given number of seconds. int sleep(int $ seconds)-将程序执行延迟给定的秒数。

I prefere to use sleep in your PHP 我更喜欢在PHP中使用sleep

    while( true ) {

        // function();

        sleep( 5 );

    }

You can stop it after 1 Minute or something like that and restart it with a cronjob. 您可以在1分钟或类似时间后将其停止,然后通过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... 您可以使用该解决方案保存资源,因为php不必一直重新启动...

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

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