Swoole提供強大的異步毫秒定時器,基于timerfd+epoll實現。主要方法:
1、swoole_timer_tick:周期性定時器,類似于JavaScript里的`setInterval() `。
2、swoole_timer_after:一次性定時器。
3、swoole_timer_clear:清除定時器。
``` php
# 周期性定時器
int swoole_timer_tick(int $ms, callable $callback, mixed $user_param);
# 一次性定時器
swoole_timer_after(int $after_time_ms, mixed $callback_function, mixed $user_param);
# 清除定時器
bool swoole_timer_clear(int $timer_id)
# 定時器回調函數
function callbackFunction(int $timer_id, mixed $params = null);
```
注意:
- `$ms` 最大不得超過 86400000。
- manager進程中不能添加定時器。
- 建議在`WorkerStart`回調里寫定時器。
定時器示例:
``` php
$server->on('WorkerStart', function (\swoole_server $server, $worker_id){
if ($server->worker_id == 0){//防止重復
//每隔2000ms觸發一次
swoole_timer_tick(2000, function ($timer_id) {
echo "tick-2000ms\n";
});
//3000ms后執行此函數
swoole_timer_after(3000, function () {
echo "after 3000ms.\n";
});
}
});
```