Current Location: Home> Latest Articles> How to use time_nanosleep in PHP to achieve sub-second pause

How to use time_nanosleep in PHP to achieve sub-second pause

gitbox 2025-05-26

When writing high-performance or time-sensitive PHP applications, sometimes we need the program to pause execution for very short periods of time, such as milliseconds or even finer microseconds or nanosecond levels. This requirement is particularly important when handling precision timing control, throttling requests, or interacting with hardware. Fortunately, PHP provides a built-in function time_nanosleep() that enables pauses that are accurate to nanoseconds. This article will take you into the deep understanding of the usage and precautions of this function, and provide multiple practical examples to help you master it flexibly.

1. What is time_nanosleep?

time_nanosleep() is a function in PHP that pauses the program to specify seconds and nanoseconds. The function signature is as follows:

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

  • $nanoseconds : Integer, indicating the number of nanoseconds to pause (between 0 and 9999999999).

This function can be used to pause any time less than one second, thereby achieving sub-second-level delay.

2. Why use time_nanosleep instead of sleep or usleep?

PHP also has two commonly used pause functions: sleep() and usleep() . The differences between them are as follows:

  • sleep(int $seconds) : Only accurate to seconds.

  • usleep(int $microseconds) : accurate to microseconds (one millionth of a second).

  • time_nanosleep(int $seconds, int $nanoseconds) : supports accurate to nanoseconds (one billionth of a second).

Therefore, time_nanosleep() is a better choice when you need higher precision time control.

3. Basic usage examples

Here is a simple example of using, pausing for 0.5 seconds (ie 500 milliseconds):

 <?php
echo "Start: " . microtime(true) . PHP_EOL;
time_nanosleep(0, 500000000); // pause 0.5 Second
echo "End: " . microtime(true) . PHP_EOL;
?>

The output will look like:

 Start: 1716026901.12345
End: 1716026901.62346

As you can see, the program paused for about 0.5 seconds.

4. Implement an accurate delay loop

Suppose you want to execute a certain piece of code every 200 milliseconds, you can use the following method:

 <?php
for ($i = 0; $i < 5; $i++) {
    echo "Tick $i at " . microtime(true) . PHP_EOL;
    time_nanosleep(0, 200000000); // 200 毫Second
}
?>

This writing method can be effectively used in scenarios such as sending throttling requests, timing output logs, polling sensors, etc.

5. Handle interrupts: Use try-catch to catch exceptions

time_nanosleep() may return in advance due to signal interruption (such as POSIX signals) in some systems and return false . In this case, a loop retry mechanism can be used.

 <?php
$seconds = 0;
$nanoseconds = 250000000; // 250 毫Second

do {
    $result = time_nanosleep($seconds, $nanoseconds);
} while ($result === false && ($error = error_get_last()) && strpos($error['message'], 'interrupted') !== false);
?>

Although most ordinary applications will not encounter such interrupts, this type of protection is recommended in multi-threaded or highly concurrency environments.

6. Combined with practical application scenarios

Suppose you are developing an API for hardware devices that needs to poll the data interface every 1 millisecond, you can write it like this:

 <?php
$url = 'https://gitbox.net/api/device/status';

for ($i = 0; $i < 1000; $i++) {
    $response = file_get_contents($url);
    echo "[$i] Response: $response" . PHP_EOL;
    time_nanosleep(0, 1000000); // 1 毫Second
}
?>

This writing method can perform high-frequency data pull without causing CPU occupation explosion.

7. Compatibility and limitations

  • time_nanosleep() has been available since PHP 5 and is available in almost all mainstream versions.

  • It can run on both Windows and UNIX-like systems.

  • Although it supports nanosecond incoming, the accuracy is actually dependent on the system clock resolution. On some platforms, the minimum accuracy may still be in microseconds.

Summarize

time_nanosleep() is a powerful but often overlooked function in PHP. It provides developers with the ability to subtly control program pause time, especially for tasks that require high time control. Through the explanation and examples of this tutorial, you should be able to master how to flexibly apply it to improve the control and performance of your application. As long as you pay attention to interrupt handling and system restrictions in use, time_nanosleep() can be used safely and accurately in various scenarios.