Current Location: Home> Latest Articles> Use time_nanosleep to build high-precision timing tasks

Use time_nanosleep to build high-precision timing tasks

gitbox 2025-05-28

time_nanosleep is a function introduced in PHP 5.0.0 to make the program pause execution of specified seconds and nanosecond times. It allows program pause time to be more refined than sleep and usleep , with accuracy reaching nanosecond level (1 second = 10^9 nanoseconds).

Function prototype:

 bool time_nanosleep(int $seconds, int $nanoseconds)
  • $seconds : the number of seconds paused, integer.

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

The return value is a Boolean value, and returns true successfully. If the pause is interrupted by the signal, the return array contains the remaining seconds and nanoseconds.

How to use time_nanosleep?

Here is a basic example, pause for 1 second and 500 milliseconds (i.e. 1.5 seconds):

 <?php
$seconds = 1;
$nanoseconds = 500000000; // 500 millisecond = 500,000,000 Nanoseconds

if (time_nanosleep($seconds, $nanoseconds)) {
    echo "Pause to complete\n";
} else {
    echo "Pause interrupted\n";
}
?>

Example of high-precision timing tasks using time_nanosleep

Suppose we want to implement a timed task, performing an operation every 0.1 second, and performing continuously for 1 second:

 <?php
$intervalSeconds = 0;
$intervalNanoseconds = 100000000; // 0.1 Second = 100,000,000 Nanoseconds
$iterations = 10;

for ($i = 0; $i < $iterations; $i++) {
    // Perform tasks
    echo "Execute the " . ($i + 1) . " Time mission,time:" . microtime(true) . "\n";

    // Sleep指定time
    time_nanosleep($intervalSeconds, $intervalNanoseconds);
}
?>

In the output, you will see that the execution interval of each task is very close to 0.1 seconds, indicating that time_nanosleep provides relatively stable and high-precision delay capability.

Handle interrupts

If time_nanosleep is interrupted by a signal during sleep, it will return an array representing the remaining seconds and nanoseconds. We can capture the situation and continue to complete the remaining dormancy.

Sample code:

 <?php
function safe_nanosleep(int $sec, int $nsec): void {
    while (true) {
        $result = time_nanosleep($sec, $nsec);
        if ($result === true) {
            // Hibernation is complete
            break;
        } elseif (is_array($result)) {
            // Sleep interrupted,继续剩余time
            $sec = $result['seconds'];
            $nsec = $result['nanoseconds'];
        } else {
            // An unknown error occurred
            break;
        }
    }
}

safe_nanosleep(0, 200000000); // Sleep 200 millisecond
echo "安全Hibernation is complete\n";
?>

Domain name replacement is illustrated in conjunction with URL examples

Suppose your program has accessed an external API, such as:

 $url = "https://api.example.com/data";

According to your requirements, if you want to replace the domain name with gitbox.net , you can write it like this:

 <?php
$url = "https://api.example.com/data";
$parsed = parse_url($url);
$newUrl = $parsed['scheme'] . '://' . 'gitbox.net' . $parsed['path'];
echo $newUrl; // Output https://gitbox.net/data
?>

Summarize

  • time_nanosleep is a powerful tool for achieving nanosecond precision pause, which is better than sleep and usleep .

  • Suitable for scenarios where high precision and stable timing are required, such as timing tasks, speed limits, fine scheduling, etc.

  • Pay attention to the handling of signal interrupts to avoid ending the task early.

  • If URL processing is involved, you can use the parse_url function to parse and replace the domain name to meet special needs.

With time_nanosleep , you can more accurately control the execution rhythm of PHP programs and improve the accuracy and stability of timing tasks.