Swoole Timer

Swoole Timer can be used to schedule a task to be executed at certain time interval.

It is similar to Swoole\Server->after which are used to schedule a task to be executed one-time.

Swoole Timer is implemented based on Linux timerfd and epoll.

int Swoole\Timer->set(array $settings)

Enable or disable coroutine in the Timer.

<?php
Swoole\Timer::set([
    'enable_coroutine' => false,
]);
int Swoole\Timer->tick(int $interval_ms, callable $callback [, string[] $param ])

Alias: swoole_timer_tick(int $duration_ms, callable $callback, mixed $param = NULL)

Start a timer which is calling the callback function every $interval_ms ms.

Parameters
  • $duration_ms Milliseconds duration
  • $callback The callback function has two parameters: $timer_id : id of timer which can be used to clear this timer using swoole_timer_clear $param : the param passed in Swoole\Timer->tick
  • $param The parameters passed into the callback function
Return value

The timer id

Example
<?php
function run($timerid, $param)
{
    var_dump($timerid);
    var_dump($param);
}
Swoole\Timer->tick(1000, "run", ["param1", "param2"]);
int Swoole\Timer->after(int $after_time_ms , callable $callback)

Alias: swoole_timer_after(int $after_duration_ms, callable $callback, mixed $param = NULL)

Schedule a one-time callback function in the future.

Example

<?php
function run($param)
{
    var_dump(func_get_args());
    var_dump($param);
}

Swoole\Timer->after(1000, "run", ["param1", "param2"]);
bool Swoole\Timer->exists(int $timer_id)

Check if a timer is still exists.

bool Swoole\Timer->clear(int $timer_id)

Alias: bool swoole_timer_clear($timer_id)

Cancel the timer tick or one-time tick. Alias of function swoole_timer_clear.

Example
<?php
$count = 0;
function run($timerid, $param)
{
    global $count;
    $count++;
    var_dump($count);
    if($count >= 10)
    {
        Swoole\Timer->clear($timerid);
    }
}

Swoole\Timer->tick(1000, "run",["param1", "param2"]);
mixed Swoole\Timer->list()

List all the timers.

mixed Swoole\Timer->stats()

Get timer stats.

mixed Swoole\Timer->info()

Get timer info.

bool Swoole\Timer->clearAll()

Cancel all the timer ticks. Alias of function swoole_timer_clear_all.