Stop a script (without fatal error) after a certain amount of query/parse time

I have a script that pulls from an external database and stores the data in a local database. I’m setup on a shared-server environment so I’m not able to let the script run for longer than two minutes, yet it would take around 5-10 minutes to run to completion.

Can I have the script stop its foreach loop after one and a half minutes, so I can redirect to the same script but with a different database offset to pick up where it left?

I can do the last part of that using a GET query string, but I’m unsure how to time it.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The easiest way would be to set a time() at the start of your script and check the difference in your foreach loop.

 $start = time(); // Returns time in seconds

 foreach($bigdata as $row) {
    if(time()-$start > 100) {  // Stop 20 seconds before 120 sec limit
       // Some code for exiting the loop...
       break;
    }
 }

Solution 2

$total_time = 0;
$start_time = microtime(true);
while($total_time < 60)//run while less than a minute
  {
    //DoSomething;
    echo $total_time."\n";
    sleep(5);//wait amount in seconds
  $total_time =  microtime(true) - $start_time ;
  } 

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply