Detecting a timeout for a block of code in PHP

后端 未结 9 1657
[愿得一人]
[愿得一人] 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 16:54

    You can't really do that if you script pauses on one command (for example sleep()) besides forking, but there are a lot of work arounds for special cases: like asynchronous queries if you programm pauses on DB query, proc_open if you programm pauses at some external execution etc. Unfortunately they are all different so there is no general solution.

    If you script waits for a long loop/many lines of code you can do a dirty trick like this:

    declare(ticks=1);
    
    class Timouter {
    
        private static $start_time = false,
        $timeout;
    
        public static function start($timeout) {
            self::$start_time = microtime(true);
            self::$timeout = (float) $timeout;
            register_tick_function(array('Timouter', 'tick'));
        }
    
        public static function end() {
            unregister_tick_function(array('Timouter', 'tick'));
        }
    
        public static function tick() {
            if ((microtime(true) - self::$start_time) > self::$timeout)
                throw new Exception;
        }
    
    }
    
    //Main code
    try {
        //Start timeout
        Timouter::start(3);
    
        //Some long code to execute that you want to set timeout for.
        while (1);
    } catch (Exception $e) {
        Timouter::end();
        echo "Timeouted!";
    }
    

    but I don't think it is very good. If you specify the exact case I think we can help you better.

提交回复
热议问题