Detecting a timeout for a block of code in PHP

后端 未结 9 1628
[愿得一人]
[愿得一人] 2021-02-02 16:44

Is there a way you can abort a block of code if it\'s taking too long in PHP? Perhaps something like:

//Set the max time to 2 seconds
$time = new TimeOut(2);
$ti         


        
9条回答
  •  盖世英雄少女心
    2021-02-02 17:11

    Cooked this up in about two minutes, I forgot to call $time->startTime(); so I don't really know exactly how long it took ;)

    class TimeOut{
        public function __construct($time=0)
        {
            $this->limit = $time;
        }
    
        public function startTime()
        {
            $this->old = microtime(true);
        }
    
        public function checkTime()
        {
            $this->new = microtime(true);
        }
    
        public function timeExpired()
        {
            $this->checkTime();
            return ($this->new - $this->old > $this->limit);
        }
    
    }
    

    And the demo.

    I don't really get what your endTime() call does, so I made checkTime() instead, which also serves no real purpose but to update the internal values. timeExpired() calls it automatically because it would sure stink if you forgot to call checkTime() and it was using the old times.

提交回复
热议问题