Detecting a timeout for a block of code in PHP

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

    You can use declare function if the execution time exceeds the limits. http://www.php.net/manual/en/control-structures.declare.php

    Here a code example of how to use

    define("MAX_EXECUTION_TIME", 2); # seconds
    
    $timeline = time() + MAX_EXECUTION_TIME;
    
    function check_timeout()
    {
        if( time() < $GLOBALS['timeline'] ) return;
        # timeout reached:
        print "Timeout!".PHP_EOL;
        exit;
    }
    
    register_tick_function("check_timeout");
    $data = "";
    
    declare( ticks=1 ){
        # here the process that might require long execution time
        sleep(5); // Comment this line to see this data text
        $data = "Long process result".PHP_EOL;
    }
    
    # Ok, process completed, output the result:
    print $data;
    

    With this code you will see the timeout message. If you want to get the Long process result inside the declare block you can just remove the sleep(5) line or increase the Max Execution Time declared at the start of the script

提交回复
热议问题