Notes
Precautions for Using Timers
-
Timers can only be added in the
onXXXXcallback. Global timers are recommended to be set in theonWorkerStartcallback, while timers specific to a connection are recommended to be set in theonConnectcallback. -
The added scheduled tasks are executed in the current process (it will not start a new process or thread). Heavy tasks may affect the current process from executing other tasks, so it is best to run time-consuming tasks in a separate process, such as creating one or more Worker processes.
-
If the current process does not have swoole/swow coroutines enabled, and the current process is busy with other tasks or if a scheduled task does not complete within the expected time, when the next execution cycle is reached, it will wait for the current task to finish before executing. This may cause the timer not to run at the expected intervals. In other words, the business tasks of the current process are executed serially, while in a multi-process scenario, tasks between processes are executed in parallel.
-
It is important to note that setting a timer in a multi-process context may lead to concurrency issues. For example, the following code will print 5 times every second.
$worker = new Worker(); // 5 processes $worker->count = 5; $worker->onWorkerStart = function(Worker $worker) { // 5 processes, each process has one such timer Timer::add(1, function(){ echo "hi\r\n"; }); }; Worker::runAll();If you only want one process to run the timer, refer to Timer::add Example 2.
-
There may be an error of about 1 millisecond.
-
Timers cannot be deleted across processes; for example, a timer set in process a cannot be directly deleted using the Timer::del interface in process b.
-
Timer IDs may be duplicated between different processes, but timer IDs generated within the same process will not be duplicated.
-
Changing the system time will affect the behavior of timers, so it is recommended to restart after changing the system time.