Alex Rivera | Logout

Detecting a timeout for a block of code in PHP

Asked 2011-09-21T01:40:22.287
15

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);
$time->startTime();

sleep(3)

$time->endTime();
if ($time->timeExpired()){
    echo 'This function took too long to execute and was aborted.';
} 

It doesn't have to be exactly like above, but are there any native PHP functions or classes that do something like this?

Edit: Ben Lee's answer with pcnt_fork would be the perfect solution except that it's not available for Windows. Is there any other way to accomplish this with PHP that works for Windows and Linux, but doesn't require an external library?

Edit 2: XzKto's solution works in some cases, but not consistently and I can't seem to catch the exception, no matter what I try. The use case is detecting a timeout for a unit test. If the test times out, I want to terminate it and then move on to the next test.

Edit
Report

1 Answer

0

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.

answered 2011-09-21T02:09:23.500

Your Answer