Swoole\Timer::after

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


Latest version: pecl install openswoole-22.1.2

Declaration

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

Parameters

interval_ms

Interval duration in milliseconds to wait before calling the callback function

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

Schedule a one-time callback function in the future after the set $interval_ms timeout.

This method is basically the same as Swoole\Timer::tick but the difference is this timer is only executed once and destroyed afterwards once it completes.

The after timer allows you to create a non-blocking task which will execute after a period of time, enabling you to continue on with your program and let the timer execute the callback once the interval is met.

See Swoole\Timer::tick for more information as they are similar in usage.

Callback Function Example

<?php

function() {
    // ...
}

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

<?php

$bar = 23;

function() 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

$str = "Swoole";
Swoole\Timer::after(1000, function() use ($str) {
    echo "Hello, $str\n";
});
Last updated on November 25, 2022