Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Use setInterval in PHP?

Tags:

php

I want to ask that how can i use php function again and again after some time automatically just like setInterval in Javascript. We set the time and it is on its job until the script is aborted or closed.

INDEX.PHP

<?
$Wall = new Wall_Updates();
$updatesarray=$Wall->Updates();
foreach($updatesarray as $data)
{
    $likes=$data['likes'];
    ?>
    <div id="likes"><?php echo $likes; ?></div>
    <?
}
?>

And Wall_Updates() Function is defined here in FUNCTION.PHP

<?php

class Wall_Updates {    
    public function Updates() {
        $myname=$_COOKIE['usename'];
        $query=mysql_query("SELECT * FROM posts WHERE name='$myname'");
        while($row=mysql_fetch_array($query))
            $data[]=$row;
        return $data;
    }
}
?>

I want this Wall_Updates() function to fetch data from mysql again and again.So, It will be Updated.

like image 662
Heart Avatar asked Oct 08 '12 14:10

Heart


People also ask

Is there setInterval in PHP?

Javascript executes setInterval in other threads to continue its code-flow execution. But php hangs on the line you have called the function that is implemented by for loops. However php supports multithreading and forking tools, but they're not recommended and not thread safety yet.

How does the setInterval () function?

setInterval() The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .

How do you run setInterval 5 times?

“setinterval for 5 times” Code Answer'svar intervalID = setInterval(alert, 1000); // Will alert every second. // clearInterval(intervalID); // Will clear the timer. setTimeout(alert, 1000); // Will alert once, after a second.


2 Answers

For the record: I think it's bad idea. But whatever :)

Try this code

function setInterval($f, $milliseconds)
{
    $seconds=(int)$milliseconds/1000;
    while(true)
    {
        $f();
        sleep($seconds);
    }
}

Usage:

setInterval(function(){
    echo "hi!\n";
}, 1000);

Or:

$a=1; 
$b=2;

setInterval(function() use($a, $b) {
    echo 'a='.$a.'; $b='.$b."\n";
}, 1000);
like image 177
Ruslan Polutsygan Avatar answered Sep 24 '22 01:09

Ruslan Polutsygan


your solution is quite simple :

   $event = new EVTimer(10,2, function() {
         Do your things .. :)
   });

https://www.php.net/manual/en/ev.examples.php

like image 39
eladcm Avatar answered Sep 23 '22 01:09

eladcm