jump to navigation

Pausing Script Execution in PHP November 12, 2011

Posted by Tournas Dimitrios in PHP.

The wrong way to pause (delay) a PHP-script is made by a long-running loop . In PHP , the Sleep function uses a special operating system call to idle the program , without ‘overloading’ the CPU . Using Sleep is an efficient way of pausing a program instead of  a processor-intensive loop (for , while) . This function  accepts one parameter of type integer  , that indicates the number of seconds you want the program to idle . Although some programming languages use milliseconds as the argument to their Sleep methods , PHP uses seconds . A few examples where “sleep()” could be used :

  • You’re running some sort of batch process that makes heavy use of a database-resource . That process has to run in the middle of the day . This may slow server down  for other users , so you modify the batch process to submit , say , 1000 database-query’s , then sleep for 15 seconds to give the database server a chance to  process any requests from other users .
  • Lets say you’ve built a crawler that uses “curl/file_get_contents ” to get remote pages . Now you don’t want to bombard the remote server with too many requests in short time . So you introduce a delay between consecutive requests .
  • Some time while testing our scripts we need to add some delay . 

Code example :

echo date('H:i:s');
echo date('H:i:s');


Keep in mind that the total excecution time of the script can’t exceed the ” max_execution_time ” of your server . Run a ” phpinfo() ”  before implementing the “sleep() ” function .


No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s