PHP EvTimer Class – Usage and Examples

by Vincy. Last modified on June 23rd, 2022.

EvTimer is a watcher class that creates an instance to run an event loop. It sets time and interval to run the event loop iterations. The time is a mandatory specification. But the interval is not. It is an optional setting applicable only for the event loop that has more than one iterations.

This article describes the following items.

  1. The basics of EvTimer.
  2. Installation and configuration
  3. The uses of this utility in PHP applications.
  4. A small example with EvTimer watcher class properties and methods.

Overview

EvTimer triggers an event after a given time. Then, it repeats the same in a periodic interval. The repeated event call in a set interval is an optional action.

We can set the priority that regulates handling multiple timers. The timer with earlier time-out will be called among the others having the same priority.

The timer avoids drifts on firing events in a loop with the configured interval. It promises a smooth and accurate event loop iteration maximum.

EvTimer Event Loop

Installation and Configuration

It does not come with the core PHP bundle. It requires the PECL Ev extension to use class.

After installing this extension, enable this extension in the PHP.ini configuration file.

extension="ev.so"

Confirm the installation and set up by echoing the phpinfo() table.

About PHP EvTimer class

The PHP documentation page provides the class synopsis of the EvTimer class. It includes properties to set the number of repeated event occurrences, time remaining.

It extends PHP EVWatcher and uses both own and inherited properties and methods.

class EvTimer extends EvWatcher {
/* EVTimer Properties */
public $repeat;
public $remaining;
/* Inherited properties from EvWatcher */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* EvTimer Methods */
public again(): void
public __construct(
     float $after ,
     float $repeat ,
     callable $callback ,
     mixed $data = null ,
     int $priority = 0 
)
final public static createStopped(
     float $after ,
     float $repeat ,
     callable $callback ,
     mixed $data = null ,
     int $priority = 0 
): EvTimer
public set( float $after , float $repeat ): void
/* Inherited methods from EvWatcher */
public EvWatcher::clear(): int
abstract public EvWatcher::__construct()
public EvWatcher::feed( int $revents ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int $revents ): void
public EvWatcher::keepalive( bool $value = ?): bool
public EvWatcher::setCallback( callable $callback ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

Properties

repeat

This is to hold the number of seconds on which the EvTimer will repeat to trigger the event. If it is 0, then the timer will not reinitiate after the time-out.

remaining

It returns the time remaining to reach the time-out or to fire the events. For the active timers, it will return the event loop time remaining to reach the timeout.

Methods

EvTimer::again()

It restarts the EvTimer watcher once in every repeat seconds as configured. If the timer is not-repeating with repeat seconds 0, then this method will not be called after a timeout.

EvTimer::__construct()

It creates an EvTimer watcher instance. It’s a four-argument constructor. The four arguments are,

  • $after – holds seconds after which the timer should trigger the event.
  • $repeat – holds seconds that defines the interval between two event loop of a timer.
  • $callback – It defines an EvWatcher callback function to be invoked for active watchers.
  • $data – data belongs to EvWatcher.
  • $priority – Integer value defines the EvTimer watcher priority.

EvTimer::createStopped()

It creates an EvTimer watcher instance in a stopped state. It will not start the watcher until calling manually. It returns the instance on successful creation.

EvTimer::set()

It configures the EvTimer watchers with the $after and $repeat seconds.

How EvTimer used in PHP applications

The EvTimer can be used in many ways in a PHP application. Some of those uses are listed below.

  • To run a Server-side countdown in an event management system.
  • Automatic message sending in a periodic interval.
  • Monitor and log socket events.
  • To run cron jobs with limited repeats.

PHP EvTimer Example

This example uses the EvTimer class’s own and inherited properties and methods.

Watcher 1 is a non-repeating timer instance whereas watcher 2 is not. The watcher 2 is created by setting $after = 5 and $repeat = 2. It calls the event after 5 seconds and repeats the same for every 2 seconds.

It prints the current iteration count on every iteration. It stops the timer once it crosses 5 iterations. The callback allows 2 more iterations further by restarting the timer using again().

It creates a stopped watcher instance. As we have seen already, it is inactive initially until we call the start() on it.

<?php
// Create watcher instance of the non-repeating timer to trigger after 5 seconds
$watcher1 = new EvTimer(5, 0, function () {
    echo "5 seconds crossed \n";
});

// Create watcher instance of the timer firing after 5 seconds
// repeats every 2 seconds
$watcher2 = new EvTimer(5, 2, function ($watcher) {
    echo "\n iteration " . Ev::iteration() . ": \n";
    echo "is fired after 5 seconds and repeats every 2 seconds, \n\n";

    // Stop the watcher after 5 iterations
    if(Ev::iteration() == 5) {
        $watcher->stop();
    }
    
    // Stop the watcher after 2 more iterations
    if(Ev::iteration() > 7) {
        $watcher->stop();
    }
    
    Ev::iteration() >= 10 and $w->stop();
});

// Create stopped timer. It turns active on an explicit start
$watcherStopped = EvTimer::createStopped(5, 2, function ($watcher) {
    echo "\n Stopped timer callback invoked. \n";

    // Stop the watcher after 5 iterations
    if(Ev::iteration() == 5) {
        $watcher->stop();
    }
});

// run loop till calling Ev::stop() or all watchers stop
Ev::run();

// Start the stopped timer that is in an inactive mode.
$watcherStopped->start();
echo "\nExecute only one iteration\n";
Ev::run(Ev::RUN_ONCE);

echo "Restart watcher2\n";
$watcher2->again();
Ev::run(Ev::RUN_NOWAIT);

echo "\nEND\n";
?>

Output

5 seconds crossed

iteration 1:
is fired after 5 seconds and repeats every 2 seconds,

iteration 2:
is fired after 5 seconds and repeats every 2 seconds,

iteration 3:
is fired after 5 seconds and repeats every 2 seconds,

iteration 4:
is fired after 5 seconds and repeats every 2 seconds,

iteration 5:
is fired after 5 seconds and repeats every 2 seconds,

Execute only one iteration

Stopped timer callback invoked.

Restart watcher2

iteration 6:
is fired after 5 seconds and repeats every 2 seconds,

iteration 7:
is fired after 5 seconds and repeats every 2 seconds,

END

Conclusion

Thus, we have seen about the PHP EvTimer and its utilities. The example created for this article used the EvTmer and EvWatcher class components.

There are pre-defined PHP constants in the EvTimer context. These constants set the behavior of the event loop, blocking and more settings of the timer.

Comments to “PHP EvTimer Class – Usage and Examples”

  • Topollo says:

    Hello

    Good Day

    Was this tutorial on windows?

    Because i can’t install it on windows at all i keep getting this error

    pecl install ev

    Notice: Trying to access array offset on value of type bool in PEAR\REST.php on line 186
    No releases available for package “pecl.php.net/ev”
    install failed

    if its in windows can you please make a tutorial on how to install

    Thanks in advance

    • Vincy says:

      Hi Topollo,

      Yes, this tutorial is on Windows. Sure, I will write an additional section on installation soon.

  • Arvin says:

    Are these tutorial pages saved in Mysql database and then retrieved. How does it work?

    • Vincy says:

      Hi Arvin,

      Yes. On first access written as an HTML file in the disk and then onwards the cached file is returned.

  • kapil says:

    Hi

    I can use it to schedule php script execution?

Leave a Reply to Topollo Cancel reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page