How To Use setInterval in PHP?

后端 未结 8 1907
刺人心
刺人心 2020-12-08 16:11

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 t

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 16:53

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

提交回复
热议问题