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));