OpenSwoole Server tick

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\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 OpenSwoole\Timer::tick, please refer to the timer documentation for more information about OpenSwoole Timers.

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

You can remove the timer later by calling OpenSwoole\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 OpenSwoole\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 OpenSwoole\Server->tick in onWorkerStart:

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