Timers in PHP

<?php

// We often want to execute PHP code at some point in the
// future, or repeatedly at some interval. PHP's built-in
// sleep() function and the pcntl_alarm() function can be used
// for these tasks. We'll look at both of these approaches.

// This function simulates a timer that waits for a specified
// number of seconds and then executes a callback.
function createTimer($seconds, $callback) {
    sleep($seconds);
    $callback();
}

// This is equivalent to Timer 1 in the original example
createTimer(2, function() {
    echo "Timer 1 fired\n";
});

// To simulate the cancellation of a timer, we'll use pcntl_alarm()
// and pcntl_signal(). This requires the pcntl extension to be enabled.

// Set up a signal handler
pcntl_signal(SIGALRM, function($signal) {
    echo "Timer 2 fired\n";
});

// Set an alarm for 1 second
pcntl_alarm(1);

// Attempt to cancel the alarm
pcntl_alarm(0);

if (pcntl_alarm(0) == 0) {
    echo "Timer 2 stopped\n";
}

// Give enough time to show Timer 2 is indeed stopped
sleep(2);

In PHP, we don’t have built-in timer objects like in some other languages. However, we can simulate similar behavior using the sleep() function and the pcntl_alarm() function (which requires the PCNTL extension).

The first “timer” is simulated using a simple function that sleeps for the specified duration and then calls a callback. This is equivalent to the blocking behavior of the first timer in the original example.

For the second timer, which demonstrates cancellation, we use pcntl_alarm(). This function schedules a SIGALRM signal to be sent to the script after a specified number of seconds. We set up a signal handler to catch this alarm and print a message.

To cancel the timer, we call pcntl_alarm(0), which cancels any previously set alarm. If the cancellation is successful (i.e., the alarm hadn’t fired yet), we print a message indicating that the timer was stopped.

Finally, we sleep for 2 seconds to give enough time to demonstrate that the second timer doesn’t fire.

To run this script:

$ php timers.php
Timer 1 fired
Timer 2 stopped

The first timer will fire after about 2 seconds, but the second timer should be stopped before it has a chance to fire.

Note that the PCNTL functions used for the second timer are not available in all PHP installations, particularly on Windows or in certain web server environments. In such cases, you might need to use alternative methods like the sleep() function or external scheduling mechanisms.