OpenSwoole\Timer::tick

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

Declaration

<?php OpenSwoole\Timer::tick(int $interval_ms, callable $callback_function, mixed ...$params = null)\:\ int|bool

Parameters

interval_ms

Interval duration in milliseconds

callback_function

Callback function to run

callback_params

The parameters passed into the callback function, this is optional

Return

timer_id

if success, it returns the timer_id

if the operation failed, it returns false

Description

Start a timer which is calling the callback function based on the $interval_ms duration which is in milliseconds.

The timer interval cannot exceed the maximum value of 86400000. The timer will continue to run until the process is stopped or when you call OpenSwoole\Timer::clear*.

A timer will remain apart of the same process space where it started from.

Callback Example

<?php

function(int $timerId) {
    // ...
}

You can also take advantage of the use anonymous syntax to pass parameters to the callback function:

<?php

$bar = 23;

function(int $timerId) use ($bar) {

    $bar += 7;

    // ...
}

The callback function will first include the ID of the timer that was started and then any parameters. You can use this ID to clear the timer.

Example

<?php

function run($timerId, $param1, $param2) {
    var_dump($timerId);
    var_dump($param);
}

OpenSwoole\Timer::tick(1000, "run", ["param1", "param2"]);
<?php

OpenSwoole\Timer::tick(3000, function (int $timerId, $param1, $param2)
{
    echo "timerId #$timerId, after 3000ms.\n";
    echo "param1 is $param1, param2 is $param2.\n";

    OpenSwoole\Timer::tick(14000, function ($timerId)
    {
        echo "timerId #$timerId, after 14000ms.\n";
    });

}, "A", "B");

The execution of the callback function does not affect the execution of the next timer interval. If a timer runs for a long period of time it may overlap the next interval. As long as the process is not blocked by the operation of a timer, others will not be affected.

If you have enabled coroutines within timers, you won't need to create the initial coroutine context, learn more about this with Timer:set.

Incorrect Usage

When using timers you must run non-blocking code or enable coroutine hooks but as an example you cannot run:

<?php
OpenSwoole\Timer::tick(3000, function () {
    echo "after 3000ms.\n";
    sleep(14);
    echo "after 14000ms.\n";
});
Last updated on November 25, 2022