Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-25.2.0 | composer require openswoole/core:22.1.5
<?php OpenSwoole\Timer::tick(int $interval_ms, callable $callback_function, mixed ...$params = null)\:\ int|bool
Interval duration in milliseconds
Callback function to run
The parameters passed into the callback function, this is optional
if success, it returns the timer_id
if the operation failed, it returns false
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.
<?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.
<?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.
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";
});