超时PHP时运行一些东西

时间:2015-10-02 13:07:31

标签: php timeout

我有疑问。 我有web请求到另一个Web服务。 但有时候,网络服务响应缓慢。

我使用SOAP来请求Web服务。

我的问题是如何在超时(约30秒)时运行某些东西(保存到DB)

谢谢......

我已经尝试了register_shutdown_function,但该功能仍然运行,即使它不是超时,... 帮帮我......

1 个答案:

答案 0 :(得分:1)

您可以尝试注册关机功能:

更新:现在应该只在脚本超时时才能正常工作。

function shutdown()
{
    $timedout = false;
    $errors = error_get_last();

    if( isset( $errors["type"] ) && $errors["type"] === E_ERROR ) {// E_ERROR => Fatal run-time errors.
        // if the code reaches this, it means, that a fatal error occurued
        // if you need to do this only when the script TIMEDOUT, you can check if message is "Maximum execution time....."
        $errorMessages = array( "Maximum execution time" );// check if this message is always the same on different PHP versions

        // just the solution for more than one specifif error messages to check
        foreach( $errorMessages as $errorMessage ) {
            // you maybe want to use, mb_strlen with the additional '8-bit' param
            // to avoid the mb.functions.overload
            $message = substr( $errors["message"], 0, strlen( $errorMessage ) );

            if( in_array( $message, $errorMessages ) ) {
                // timeout message occurred
                $timedout = true;
            }

        }
    }

    // we got a fatal error, probably a timeout
    if( $timedout ) {
        echo 'Script executed with success';
        echo "<pre>";
        var_dump( $errors );
    }

}

register_shutdown_function('shutdown');

//note: this below is just my test
set_time_limit( 2 );

while( true ) {
    // do nothing
}

我的输出:

Fatal error: Maximum execution time of 2 seconds exceeded in some.php on line 11
Script executed with success