Current Location: Home> Latest Articles> Use time_nanosleep to achieve accurate sleep time control

Use time_nanosleep to achieve accurate sleep time control

gitbox 2025-05-28

In PHP, we often need to pause the program for a period of time, which is very common when dealing with polling, timing tasks, or speed limit operations. Usually, people will use the sleep() function to achieve this, but the time unit of sleep() is seconds, which cannot meet the precise control requirements for milliseconds or even nanoseconds. At this time, PHP provides the time_nanosleep() function, which allows you to control the pause time with the accuracy of seconds and nanoseconds.

What is time_nanosleep() ?

time_nanosleep() is a function provided in PHP 5.0.0 and above to make the current process pause the specified number of seconds and nanoseconds. Compared to sleep() , it can only be accurate to seconds, time_nanosleep() allows you to control the pause time more flexibly.

The function definition is as follows:

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

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

If the pause is successful, the function returns true , and if it is interrupted by a signal in the middle, it returns an array containing the remaining time.

Example of usage

Here is a simple example of how to pause for 1 second and 500 milliseconds (i.e. 1.5 seconds):

 <?php
echo "Start time:" . microtime(true) . PHP_EOL;

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

if (time_nanosleep($seconds, $nanoseconds)) {
    echo "Sleep end time:" . microtime(true) . PHP_EOL;
} else {
    echo "Sleep interrupted" . PHP_EOL;
}
?>

The run result will show the timestamp twice, with a time difference of about 1.5 seconds.

Handle interrupts

If time_nanosleep() is interrupted by the system signal, an array will be returned containing the remaining seconds and nanoseconds. You can call time_nanosleep() again according to the return value to continue sleeping. Examples are as follows:

 <?php
$seconds = 2;
$nanoseconds = 0;

while (true) {
    $result = time_nanosleep($seconds, $nanoseconds);
    if ($result === true) {
        echo "Sleep complete" . PHP_EOL;
        break;
    } elseif (is_array($result)) {
        echo "Sleep interrupted,time left:{$result['seconds']}Second {$result['nanoseconds']}Nanoseconds" . PHP_EOL;
        $seconds = $result['seconds'];
        $nanoseconds = $result['nanoseconds'];
    } else {
        echo "Failed to sleep" . PHP_EOL;
        break;
    }
}
?>

This writing ensures that the program can continue to complete the predetermined sleep time after being interrupted by a signal.

Examples of usage scenarios combined with HTTP requests

Suppose you want to implement a request speed limit function, pausing for 200 milliseconds between each request, you can send a request in conjunction with curl and use time_nanosleep() to accurately control the interval time. Here is the sample code:

 <?php
$urls = [
    "https://gitbox.net/api/data1",
    "https://gitbox.net/api/data2",
    "https://gitbox.net/api/data3",
];

foreach ($urls as $url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo "Request failed:" . curl_error($ch) . PHP_EOL;
    } else {
        echo "Request succeeded:" . substr($response, 0, 50) . "..." . PHP_EOL;
    }
    curl_close($ch);

    // pause 200 millisecond
    time_nanosleep(0, 200000000);
}
?>

This code requests three interfaces in turn, pausing for 200 milliseconds after each request, thus avoiding too frequent requests.

Summarize

  • time_nanosleep() allows you to pause PHP programs with seconds and nanosecond precision.

  • It is more flexible than traditional sleep() and usleep() , and is suitable for scenarios with high requirements for time control accuracy.

  • Pay attention to handling signal interrupts to ensure the robustness of program logic.

  • time_nanosleep() is a very practical function when speed limiting, interval control or fine scheduling is required.

By rationally using time_nanosleep() , your PHP applications can be more accurate and efficient in time control.