2017-04-14 107 views
1

我想运行每10秒的PHP代码,但我的代码有问题PHP:运行PHP代码每10秒

因为函数是随机的延迟(2秒至5秒)

我想确切运行

for($i=0;$i<=5;$i++){ 
    echo date('Y-m-d H:i:s').'<br />'; 
    get_file_content('....'); //load file from server (make 2 seconds until 5 seconds) 
    sleep(10); // sleep for 10 seconds 
} 

结果1::

如果超时或者如果更5秒

代码上10秒代码并传递函数

2017-04-14 15:25:35 
2017-04-14 15:25:46 
2017-04-14 15:25:57 
2017-04-14 15:26:08 
2017-04-14 15:26:19 
2017-04-14 15:26:30 

另一个结果:

2017-04-14 15:32:22 
2017-04-14 15:32:34 
2017-04-14 15:32:44 
2017-04-14 15:33:01 
2017-04-14 15:33:17 
2017-04-14 15:33:29 

我想要得到这样的结果(即使加载文件做了很长时间)

确切的结果:

2017-04-14 15:25:00 
2017-04-14 15:25:10 
2017-04-14 15:25:20 
2017-04-14 15:25:30 
2017-04-14 15:25:40 
2017-04-14 15:25:50 
+3

想想cronjobs。 – tilz0R

+0

我使用cron作业,但我的服务器限于1分钟 –

回答

2

如何在东西线:

for($i=0;$i<=5;$i++){ 
$previousTime = date(); 
echo date('Y-m-d H:i:s').'<br />'; 
get_file_content('....'); //load file from server (make 2 seconds until 5 seconds) 
sleep(10-(date()-$previousTime)); 
} 
+0

谢谢。如果file_get_content加载超过10秒? –

+0

然后'我想每10秒运行一次php代码,但是我的代码有问题'需要定义好一点。 – fzd

0

只需计算file_get_contents需要多长时间。

echo date('Y-m-d H:i:s').'<br />'; 
$start = time(); 
get_file_content('....'); //load file from server (make 2 seconds until 5 seconds) 
$end = time(); 
$diff = $end - $start; 
if ($diff < 10) sleep(10 - $diff); // sleep for (10 - the amount how long the get took) seconds 
// Skip if longer than 10 
0

试算执行你的函数

for($i=0;$i<=5;$i++){ 
    echo date('Y-m-d H:i:s').'<br />'; 
    $start = time(); 
    get_file_content('....'); //load file from server (make 2 seconds until 5 seconds) 
    $time_elapsed = time() - $start; 
    if ($time_elapsed>0 || $time_elapsed<=10) sleep(10- $time_elapsed); 
} 

更精确,使用microtime所需要的时间。

0

我找到解决办法:

$context = array('http' => array('timeout' => 10)); 
$data = file_get_contents('...',false,stream_context_create($context));