Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

give each loop 30 sec execution time

Tags:

php

I have my application hosted in Siteground, in a shared host. I have build a cron job that executes a php file every night. The problem is that that file contains a main loop that executes the code, 85 times. More precisely, i take arrays of data and manipulate them. This is done 85 times. Something like this:

<?php
$main_array = array("//85 elements");
foreach ($main_array as $var){

 $array1 = array ("//a lot of data");
//manipulate array1

}
?>

Since there are many manipulations of the taken data, it takes 2 minutes and 5' to completely execute. By any chance.. is there a way to set the execution time 30 sec for each "foreach" loop?? I can't move to dedicated host, so i need to figure something else out..

Thanks in advace

like image 516
Mirela Avatar asked Dec 03 '25 23:12

Mirela


2 Answers

Use microtime() to evaluate running time of each loop.

<?php
$main_array = array("//85 elements");
foreach ($main_array as $var){
  $time_start = microtime(true);
  $array1 = array ("//a lot of data");
  //manipulate array1
  $time_end = microtime(true);
  $time = $time_end - $time_start;
  //check sometimes in your script whether execution time is reached
  if($time > 30){
    break; //or continue; which you want
  }
}
?>

http://php.net/manual/en/function.microtime.php

But the execution time is really long, what is sour script calculating? Maybe there are much more effective ways to do so...

like image 190
Karl Adler Avatar answered Dec 05 '25 12:12

Karl Adler


set_time_limit(30); //Enter the value in seconds

Check set_time_limit() in php

like image 38
Deepu Avatar answered Dec 05 '25 12:12

Deepu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!