Current Location: Home> Latest Articles> Create PHP timer function with time_nanosleep

Create PHP timer function with time_nanosleep

gitbox 2025-05-28

There are many ways to implement the timer function in PHP. The time_nanosleep function is a very accurate sleep function that allows scripts to pause execution of specified seconds and nanoseconds, so it can be used to implement high-precision timers. This article will explain in detail how to use the time_nanosleep function to create a simple timer.

What is time_nanosleep ?

The time_nanosleep function is used to pause the specified time by the currently executed script. The units of time include seconds and nanoseconds. The syntax is as follows:

 bool time_nanosleep(int $seconds, int $nanoseconds)
  • $seconds : The number of seconds paused, non-negative integer.

  • $nanoseconds : The number of nanoseconds paused, ranging from 0 to 999,999,999.

The function returns true to indicate that normal sleep is completed, and returns false when it fails, or an error is triggered.

Use scenarios

time_nanosleep is very suitable for scenarios where precise control of the waiting time is required, such as:

  • Implement high-precision timer

  • Control the execution frequency

  • Avoid CPU idle and reduce resource waste

Implementing a simple timer example

In the following example, we will implement a timer that outputs a timestamp every specified number of milliseconds until the total time is reached.

 <?php

/**
 * Simple timer function,Execute tasks at specified intervals
 * 
 * @param int $interval_ms Interval time,Unit milliseconds
 * @param int $total_duration_ms Total time,Unit milliseconds
 */
function simple_timer(int $interval_ms, int $total_duration_ms)
{
    $start_time = microtime(true);
    $elapsed = 0;

    while ($elapsed < $total_duration_ms / 1000) {
        // Calculate sleep seconds and nanoseconds
        $seconds = intdiv($interval_ms, 1000);
        $nanoseconds = ($interval_ms % 1000) * 1000000;

        // Sleep specified time
        time_nanosleep($seconds, $nanoseconds);

        // Output current timestamp and run time
        $current_time = microtime(true);
        $elapsed = $current_time - $start_time;
        echo "Elapsed: " . round($elapsed, 3) . " seconds\n";
    }

    echo "Time end!\n";
}

// Every other 500 Execute once in milliseconds,continued 5 Second
simple_timer(500, 5000);

Code parsing

  • Use microtime(true) to get the high-precision current time.

  • Call time_nanosleep in the loop to pause the script for the specified time.

  • Calculate the run time and print it.

  • Cycle until the total duration of the set is reached.

Things to note

  • time_nanosleep may be interrupted by the signal. If it is interrupted, the function will return false and trigger a warning. The signal can be captured using the pcntl function to ensure stability.

  • The accuracy of nanoseconds depends on the operating system, and not all systems support very fine nanosecond-level sleep.

  • In some environments, the accuracy and effect of usleep and time_nanosleep may not differ much.

Combined with remote resource examples

If you need to access the remote interface through PHP and combine the timer to make periodic requests, you can use the following code example:

 <?php

function fetch_data_periodically($url, $interval_ms, $times)
{
    for ($i = 0; $i < $times; $i++) {
        // Send a request
        $response = file_get_contents($url);
        echo "Response #$i: " . substr($response, 0, 50) . "...\n";

        // Sleep
        $seconds = intdiv($interval_ms, 1000);
        $nanoseconds = ($interval_ms % 1000) * 1000000;
        time_nanosleep($seconds, $nanoseconds);
    }
}

$url = "https://gitbox.net/api/data";
fetch_data_periodically($url, 1000, 3);

This code requests the interface on gitbox.net every 1 second and executes 3 times in a row.