Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 4th, 2012  |  syntax: None  |  size: 1.84 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Detecting a timeout for a block of code in PHP
  2. //Set the max time to 2 seconds
  3. $time = new TimeOut(2);
  4. $time->startTime();
  5.  
  6. sleep(3)
  7.  
  8. $time->endTime();
  9. if ($time->timeExpired()){
  10.     echo 'This function took too long to execute and was aborted.';
  11. }
  12.        
  13. $pid = pcntl_fork();
  14. if ($pid == 0) {
  15.     // this is the child process
  16. } else {
  17.     // this is the parent process, and we know the child process id is in $pid
  18. }
  19.        
  20. $pid = pcntl_fork();
  21. if ($pid == 0) {
  22.     // this is the child process
  23.     // run your potentially time-consuming method
  24. } else {
  25.     // this is the parent process, and we know the child process id is in $pid
  26.     sleep(2); // wait 2 seconds
  27.     posix_kill($pid, SIGKILL); // then kill the child
  28. }
  29.        
  30. declare(ticks=1);
  31.  
  32. class Timouter {
  33.  
  34.     private static $start_time = false,
  35.     $timeout;
  36.  
  37.     public static function start($timeout) {
  38.         self::$start_time = microtime(true);
  39.         self::$timeout = (float) $timeout;
  40.         register_tick_function(array('Timouter', 'tick'));
  41.     }
  42.  
  43.     public static function end() {
  44.         unregister_tick_function(array('Timouter', 'tick'));
  45.     }
  46.  
  47.     public static function tick() {
  48.         if ((microtime(true) - self::$start_time) > self::$timeout)
  49.             throw new Exception;
  50.     }
  51.  
  52. }
  53.  
  54. //Main code
  55. try {
  56.     //Start timeout
  57.     Timouter::start(3);
  58.  
  59.     //Some long code to execute that you want to set timeout for.
  60.     while (1);
  61. } catch (Exception $e) {
  62.     Timouter::end();
  63.     echo "Timeouted!";
  64. }
  65.        
  66. class TimeOut{
  67.     public function __construct($time=0)
  68.     {
  69.         $this->limit = $time;
  70.     }
  71.  
  72.     public function startTime()
  73.     {
  74.         $this->old = microtime(true);
  75.     }
  76.  
  77.     public function checkTime()
  78.     {
  79.         $this->new = microtime(true);
  80.     }
  81.  
  82.     public function timeExpired()
  83.     {
  84.         $this->checkTime();
  85.         return ($this->new - $this->old > $this->limit);
  86.     }
  87.  
  88. }