异步运行PHP

时间:2012-10-05 04:50:55

标签: php asynchronous

给定PHP中的输入和按钮,我需要在输入中输入一段时间,然后按下按钮,它应该在这段时间后执行PHP函数。

我该怎么做?

编辑:

我不需要客户端解决方案。这是服务器端问题。

当用户离开页面时,JavaScript的超时终止。用户离开页面后,我需要超时仍然存在。

我没有尝试任何东西,我不知道怎么做。

2 个答案:

答案 0 :(得分:1)

由于几乎所有时间都使用数据库中的数据,creating an event in mysql可能是一种选择。此外,如果你设法用mysql代码编写所有代码,那么它会比从php到mysql的来回快。

答案 1 :(得分:1)

我最近有类似的需求。不确定这是否适合你。让我知道它是否有效。

if (isset($_GET['async'])) {

    for( $i = 0 ; $i < 10 ; $i++ )
    {
        append_log(date('l jS \of F Y h:i:s A') . ': background process.<br />');
        sleep(1);
    }

    exit;
}

header( 'Content-type: text/html; charset=utf-8' );
pseudo_async(array('async' => true));   // this runs this php script in the backbround

echo 'Begin ...<br />';
for( $i = 0 ; $i < 10 ; $i++ )
{
    output_buffer('appended to the log <br />');
    append_log(date('l jS \of F Y h:i:s A') . ': main process.<br />');
    sleep(1);
}
echo 'End ...<br />';


function pseudo_async($query) {

    $timeout = array('http' => array('timeout' => 0.01));
    $context = stream_context_create($timeout);

    @file_get_contents(selfurl() . '?' . http_build_query($query), false, $context);
}

function append_log($msg) {
    $file = __DIR__ . '/log.html';
    file_put_contents($file, $msg, FILE_APPEND);
}

function selfurl() {
    $pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
    if ($_SERVER["SERVER_PORT"] != "80")
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    else 
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    return $pageURL;
}

function output_buffer($str) {
    echo $str;
    flush();
    ob_flush(); 
}
相关问题