Our blog

 

PHP Random Sleep Function with Flush

Sometimes you want your script to pause for a short period of time before repeating a loop or proceeding to the next step. This may be to reduce server load or even to simulate the natural pauses that a person would make whilst browsing a site. This kind of thing is especially true if you are building a system to scrape content such as product information from a suppliers web site and you do not want to hammer their server to death and get your IP banned.

PHP:
  1. function sleep_flush($chunks=10){
  2.  
  3.     $c=0;
  4.  
  5.     while($c <$chunks){
  6.  
  7.        $rand = rand(2000000, 6000000);
  8.  
  9.        echo '<br> . . . sleeping for ' . round(($rand / 1000000),2) . ' seconds . . . zzzzzzzzzzzzzz<br>';
  10.  
  11.        flush();
  12.  
  13.        usleep($rand);
  14.  
  15.        $c++;
  16.  
  17.     }
  18.  
  19. }

This function will do just that for you. Also it has a built in flush which will help in preventing the script from being regarded as timed out if you are running it from the web browser.

More Reading:

  • no matching posts found..

 

Leave a Reply