As alternative, php has a built-in timer controller: new EvTimer()
.
It can be used to make a task scheduler, with proper handling of special cases.
This is not only the Time, but a time transport layer, a chronometer, a lap counter, just as a stopwatch but with php callbacks ;)
EvTimer watchers are simple relative timers that generate an event
after a given time, and optionally repeating in regular intervals
after that.
The timers are based on real time, that is, if one registers an event
that times out after an hour and resets the system clock to January
last year, it will still time out after(roughly) one hour.
The callback is guaranteed to be invoked only after its timeout has
passed (...). If multiple timers become ready during
the same loop iteration then the ones with earlier time-out values are
invoked before ones of the same priority with later time-out values.
The timer itself will do a best-effort at avoiding drift, that is, if
a timer is configured to trigger every 10 seconds, then it will
normally trigger at exactly 10 second intervals. If, however, the
script cannot keep up with the timer because it takes longer than
those 10 seconds to do) the timer will not fire more than once per
event loop iteration.
The first two parameters allows to controls the time delay before execution, and the number of iterations.
The third parameter is a callback function, called at each iteration.
after
Configures the timer to trigger after after seconds.
repeat
If repeat is 0.0 , then it will automatically be stopped once the timeout is reached.
If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.
https://www.php.net/manual/en/class.evtimer.php
https://www.php.net/manual/en/evtimer.construct.php
$w2 = new EvTimer(2, 1, function ($w) {
echo "is called every second, is launched after 2 seconds\n";
echo "iteration = ", Ev::iteration(), PHP_EOL;
// Stop the watcher after 5 iterations
Ev::iteration() == 5 and $w->stop();
// Stop the watcher if further calls cause more than 10 iterations
Ev::iteration() >= 10 and $w->stop();
});
We can of course easily create this with basic looping and some tempo with sleep()
, usleep()
, or hrtime()
, but new EvTimer()
allows cleans and organized multiples calls, while handling special cases like overlapping.