Swoole Server tick

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\Server->tick(int $milliseconds, mixed $callback): int

Parameters

milliseconds

The timer tick interval in milliseconds, the timer will keep running using this interval

callback

The callback that the timer will run everytime the interval is met

Return

timerId

If success, it returns a unique ID of the timer, otherwise it returns false.

Description

Trigger a timer tick by interval (set in milliseconds). This method is just an alias of function Swoole\Timer::tick, please refer to the timer documentation for more information about Swoole Timers.

A Timer will be destroyed once its worker process where it started from ends.

You can remove the timer later by calling Swoole\Timer::clear(int $timerId).

If the server reloads ro restarts, timers are stopped. If timers are handling critical data, you should implement some functionality to gracefully bring down the timers upon the onWorkerStop event.

Example

Use the Swoole\Server->tick in onReceive:

<?php
function onReceive($server, $fd, $from_id, $data)
{
    $server->tick(1000, function() use ($server, $fd)
    {
        $server->send($fd, "hello world");
    });
}

Use the Swoole\Server->tick in onWorkerStart:

<?php
function onWorkerStart(Swoole\Server $server, $worker_id)
{
    $server->tick(1000, function ($id)
    {
        var_dump($id);
    });
}
Last updated on August 31, 2022