Search code examples
phpsocketsloopsdelay

Call function every 10 seconds while being in a loop


Basically, I have a socket and a while loop to constantly get it's data, like this:

while (TRUE)
{ 
    $read = fgets($fp); //get data
    if (preg_match("/:(\S+)!\S+@\S+ JOIN (#\S+)/i", $read, $match)) { user_joined($match[1],    $match[2]); } //JOIN
    if (preg_match("/:(\S+)!\S+@\S+ PART (#\S+)/i", $read, $match)) { user_parted($match[1], $match[2]); } //PART
    if (preg_match("/:(\S+)!\S+@\S+ PRIVMSG (#\S+) :(.*)/i", $read, $match)) { inc_message($match[1], $match[2], $match[3]); } //MESSAGE
    if (preg_match("/:jtv!jtv@\S+ PRIVMSG $nick :(\S+)/i", $read, $match)){jtv_error($match[1]);} //JTV WARNING
    if (preg_match("/PING :.*/i", $read, $match)) { fwrite($fp, "PONG :$match[1]\r\n"); } //respond to server
}

Now, I also want to execute a function every 10 seconds to reset some vars. How can I do this without really blocking the loop? If it's blocked for like 0.1 seconds I don't mind.


Solution

  • PHP performs quite badly when trying to do realtime stuff. What you could do is get the time before the beginning of the loop, wait a bit after your code has executed (to prevent huge CPU load) and get the time after that :

    $timeCursor = microtime(true);
    
    while (TRUE)
    { 
        $read = fgets($fp); //get data
        if (preg_match("/:(\S+)!\S+@\S+ JOIN (#\S+)/i", $read, $match)) { user_joined($match[1],    $match[2]); } //JOIN
        if (preg_match("/:(\S+)!\S+@\S+ PART (#\S+)/i", $read, $match)) { user_parted($match[1], $match[2]); } //PART
        if (preg_match("/:(\S+)!\S+@\S+ PRIVMSG (#\S+) :(.*)/i", $read, $match)) { inc_message($match[1], $match[2], $match[3]); } //MESSAGE
        if (preg_match("/:jtv!jtv@\S+ PRIVMSG $nick :(\S+)/i", $read, $match)){jtv_error($match[1]);} //JTV WARNING
        if (preg_match("/PING :.*/i", $read, $match)) { fwrite($fp, "PONG :$match[1]\r\n"); } //respond to server
    
        usleep(50000); // do nothing for 50 ms
    
        $currentTime = microtime(true);
        if ($timeCursor + 10 <= $currentTime) {
            $timeCursor = $currentTime;
            // here you can call a function every 10s
        }
    }