Home > Hosting > System

How does swoole realize the timing task

2024-01-27 22:14:49

Methods: 1. Use the swoole_timer_after (time, executed function) statement to execute the task after the specified time; 2. Set an interval clock timer to execute tasks regularly by using the swoole_timer_tick (time, executed function, callback function) statement.

Operating environment of this course: Windows S10 system, Swoole4 version 4 and DELL G3 computer.

How does swoole realize the timed task swoole_timer_after?

To execute the function after the specified time, swoole-1.7.7 or above is required.

swoole_timer_after(int $after_time_ms, mixed $callback_function);

The swoole_timer_after function is a one-time timer that will be destroyed after execution. This function is different from the sleep function provided by the PHP standard library. after is non-blocking. After the sleep call, the current process will be blocked and will not be able to process new requests.

$after_time_ms specifies the time in milliseconds.

The function executed after the expiration of $callback_function time must be callable. The callback function does not accept any parameters.

The maximum amount of $after_time_ms shall not exceed 86400000.

Use examples

swoole_timer_after(1000, function(){ echo "timeoutn"; });

swoole_timer_tick

Set an interval clock timer, which is different from the after timer in that the tick timer will continue to trigger until swoole_timer_clear is called to clear. Unlike swoole_timer_add, tick timer can have multiple timers with the same interval.

int swoole_timer_tick(int $ms, mixed $callback, mixed $param = null);

$ TERM specifies the time in milliseconds

The function executed after the expiration of $callback_function time must be callable. The callback function does not accept any parameters.

$param callback parameter

The maximum number of $ms shall not exceed 86,400,000.

Tick timer is available above version 1.7.14.

Tick timer is about to replace swoole_timer_add.

call-back function

The callback function triggered by the timer accepts two parameters.

function onTimer(int $timer_id, mixed $params = null);

The ID of the $timer_id timer, which can be used for swoole_timer_clear to clear this timer.

$params user parameters passed in by swoole_timer_tick.

Use examples

swoole_timer_tick(1000, function(){ echo "timeoutn"; });

Recommended study: swoole tutorial


Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us