How To Use setInterval in PHP?

后端 未结 8 1905
刺人心
刺人心 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);
    
    0 讨论(0)
  • 2020-12-08 16:53

    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.

    0 讨论(0)
  • 2020-12-08 16:54

    I will surgest that you use a cron job to implement such functionality in your code. Cron will run in the background based on the instruction you give it. check out this article

    0 讨论(0)
  • 2020-12-08 16:56

    It isn't clear what you want to achieve exactly.

    Are you aware that PHP only delivers content on request?

    If you want the server to update something once in a while (a file for example), use a cronjob (on *nix).

    If you want your WEBPAGE to re-query something, do it in javascript and call a PHP script that delivers fresh content.

    0 讨论(0)
  • 2020-12-08 16:58

    your solution is quite simple :

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

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

    0 讨论(0)
  • 2020-12-08 17:05

    since the asynchronous concept of web development has to do with effecting the changes on a web page without reloading the page, we must not always run to the bays of Ajax when ever we need such effects on our web pages, PHP can simply do the job of going to the database @ sleep seconds to retrieve some sets of data for our usage especially for chat application purposes. See the below codes:

    function setInterval ( $func, $seconds ) 
    {
          $seconds = (int)$seconds;
          $_func = $func;
          while ( true )
          {
                $_func;
                sleep($seconds);
          }
    }
    

    Now, let's say we have a function get_msg() that goes to the database to download some sets of information, if we must do that repeatedly without the repeated usage of button calls, then, see the usage of the setInterval function written above with the get_msg function.

    setInterval ( get_msg(), 5 );
    
    0 讨论(0)
提交回复
热议问题