Home > Article > PHP Framework > How to implement scheduled tasks in swoole
Method: 1. Use the "swoole_timer_after (time, function to be executed)" statement to execute the task after the specified time; 2. Use the "swoole_timer_tick (time, function to be executed, callback function)" statement to set an interval The clock timer executes tasks regularly.
The operating environment of this tutorial: Windows10 system, Swoole4 version, DELL G3 computer
swoole_timer_after
Execute the function after the specified time, which requires swoole-1.7.7 or above.
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 is completed. This function is different from the sleep function provided by the PHP standard library. After is non-blocking. After the sleep call is made, the current process will be blocked and will not be able to handle new requests.
$after_time_ms specifies the time in milliseconds
$callback_function The function executed after the time expires must be callable. The callback function does not accept any parameters
$after_time_ms must not exceed 86400000
Usage example
swoole_timer_after(1000, function(){ echo "timeout\n"; });
swoole_timer_tick
Set an interval clock timer. Unlike the after timer, the tick timer will continue to trigger until it is cleared by calling swoole_timer_clear. Different from swoole_timer_add, the tick timer can have multiple timers with the same interval.
int swoole_timer_tick(int $ms, mixed $callback, mixed $param = null);
$ms Specifies the time in milliseconds
$callback_function The function executed after the time expires must be callable. The callback function does not accept any parameters
$param callback parameters
$ms The maximum value shall not exceed 86400000
Tick timer is available in version 1.7.14 or above
Tick timer will soon replace swoole_timer_add
Callback function
The callback function triggered by the timer accepts 2 parameters.
function onTimer(int $timer_id, mixed $params = null);
$timer_id The ID of the timer, which can be used to swoole_timer_clear to clear this timer
$params User parameters passed in by swoole_timer_tick
Usage examples
swoole_timer_tick(1000, function(){ echo "timeout\n"; });
Recommended learning: swoole tutorial
The above is the detailed content of How to implement scheduled tasks in swoole. For more information, please follow other related articles on the PHP Chinese website!