简体   繁体   中英

Running PHP asynchronously

Given an input and a button in PHP, I need to enter an amount of time in the input and then press the button, it should execute a PHP function after that amount of time.

How do I do this?

EDIT:

I don't need a client-side solution. This is a server-side problem.

The JavaScript's timeout dies when the user leaves the page. I need that timeout still alive after the user leaves the page.

I haven't tried anything anything, I don't know how do this.

Since almost all the time you work with data in the database, creating an event in mysql might be an option. Furthermore if you manage to write all in mysql code, it would be faster than going back and forth from php to mysql.

I've recently had a similar need. Not sure if this works for you though. Let me know if it works or not.

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(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM