Is there a function similar to setTimeout() (JavaScript) for PHP?

前端 未结 9 1537
离开以前
离开以前 2020-12-06 16:08

The question sort of says it all - is there a function which does the same as the JavaScript function setTimeout() for PHP? I\'ve searched

9条回答
  •  臣服心动
    2020-12-06 16:52

    A few things I'd like to note about timers in PHP:

    1) Timers in PHP make sense when used in long-running scripts (daemons and, maybe, in CLI scripts). So if you're not developing that kind of application, then you don't need timers.

    2) Timers can be blocking and non-blocking. If you're using sleep(), then it's a blocking timer, because your script just freezes for a specified amount of time. For many tasks blocking timers are fine. For example, sending statistics every 10 seconds. It's ok to block the script:

    while (true) {
        sendStat();
        sleep(10);
    }
    

    3) Non-blocking timers make sense only in event driven apps, like websocket-server. In such applications an event can occur at any time (e.g incoming connection), so you must not block your app with sleep() (obviously). For this purposes there are event-loop libraries, like reactphp/event-loop, which allows you to handle multiple streams in a non-blocking fashion and also has timer/ interval feature.

    4) Non-blocking timeouts in PHP are possible. It can be implemented by means of stream_select() function with timeout parameter (see how it's implemented in reactphp/event-loop StreamSelectLoop::run()).

    5) There are PHP extensions like libevent, libev, event which allow timers implementation (if you want to go hardcore)

提交回复
热议问题