Reputation: 285
I want run php code every 10 seconds, but my code have a problem
Because functions are random delay ( 2 seconds until 5 seconds )
I want exact run code on 10 seconds and passes function if time out or if more 5 seconds
Code :
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
}
Result 1 :
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
Another Result :
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
I want get this result ( even load file make a long time )
Exact result :
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
Upvotes: 1
Views: 4223
Reputation: 285
I find solution :
$context = array('http' => array('timeout' => 10));
$data = file_get_contents('...',false,stream_context_create($context));
Upvotes: 0
Reputation: 137
try to count time needed to execute your function
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);
}
for more accurate, use microtime
.
Upvotes: 1
Reputation: 1879
Just calculate how long the file_get_contents
took.
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
Upvotes: 0
Reputation: 845
How about something in the lines of :
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));
}
Upvotes: 3