Settimeout Php Code Example

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 php.net, and I can”t seem to find any…

Đang xem: Settimeout and setinterval: call a function after a period of time

*

There is no way to delay execution of part of the code of in the current script. It wouldn”t make much sense, either, as the processing of a PHP script takes place entirely on server side and you would just delay the overall execution of the script. There is sleep() but that will simply halt the process for a certain time.

You can, of course, schedule a PHP script to run at a specific time using cron jobs and the like.

*

There”s the sleep function, which pauses the script for a determined amount of time.

See also usleep, time_nanosleep and time_sleep_until.

Xem thêm: array map php

*

PHP isn”t event driven, so a setTimeout doesn”t make much sense. You can certainly mimic it and in fact, someone has written a Timer class you could use. But I would be careful before you start programming in this way on the server side in PHP.

*

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.

Xem thêm: Tổng Hợp Bài Tập Php Căn Bản Có Lời Giải, Bài Tập Hàm Trong Php

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)

Leave a Comment

DMCA.com Protection Status