Current Location: Home> Latest Articles> time_nanosleep rhythm control instance in file processing

time_nanosleep rhythm control instance in file processing

gitbox 2025-05-27

time_nanosleep is a built-in function in PHP that allows the current process to sleep with the specified number of seconds and nanoseconds. Its function signature is as follows:

 bool time_nanosleep(int $seconds, int $nanoseconds)
  • $seconds : integer seconds, second part of sleep time.

  • $nanoseconds : nanoseconds, ranging from 0 to 999,999,999.

Compared with the traditional sleep function, it can only implement second-level delay, time_nanosleep supports nanosecond-level delay, achieving more accurate time control.

2. Scenario description

Suppose you want to pause for an exact period of time (such as 500 milliseconds) when processing a large number of files to prevent excessive I/O pressure from being too high or network service frequency limits. time_nanosleep can meet this requirement.

3. Sample code analysis

The following example shows how to use time_nanosleep to pause 500 milliseconds after processing files when traversing folders.

 <?php

$directory = '/path/to/your/files';

// Open the directory handle
if ($handle = opendir($directory)) {
    while (false !== ($file = readdir($handle))) {
        // Ignore special directories
        if ($file === '.' || $file === '..') {
            continue;
        }

        $filePath = $directory . DIRECTORY_SEPARATOR . $file;

        // File processing operations are performed here
        echo "Processing file: $filePath\n";
        // Simulate file processing time
        // file_get_contents, file_put_contents, Or other operations

        // Sleep500millisecond,Prevent processing too fast
        $seconds = 0;
        $nanoseconds = 500 * 1000000; // 500millisecond = 500,000,000Nanoseconds
        time_nanosleep($seconds, $nanoseconds);
    }
    closedir($handle);
}

?>

Code description:

  • Iterates through all files in the specified directory.

  • After processing each file, a 500-ms pause is achieved through time_nanosleep(0, 500000000) .

  • This ensures that the processing rhythm is even and avoids performance bottlenecks caused by a large number of file operations in an instant.

4. Things to note

  • time_nanosleep 's support for accuracy depends on the operating system and PHP environment, and the actual sleep time may be slightly biased, but it can usually meet most precise control needs.

  • The nanosecond parameter range is limited to 0-999,999,999,999, which will cause a warning if you are out of range.

  • If you need to interrupt sleep, you can use time_sleep_until or signal processing mechanism to implement it.

5. Combined with URL request rhythm control example

In some scenarios, such as when batch calling API, time_nanosleep can also be used to control the request frequency to prevent the request from being restricted due to excessively fast. For example:

 <?php

$urls = [
    'https://gitbox.net/api/data1',
    'https://gitbox.net/api/data2',
    'https://gitbox.net/api/data3',
];

foreach ($urls as $url) {
    // Send a request(Schematic)
    echo "Fetching data from: $url\n";
    // For example file_get_contents($url) or curl ask

    // Sleep200millisecond,防止ask过快
    time_nanosleep(0, 200 * 1000000);
}

?>

6. Summary

The time_nanosleep function is a very useful tool in PHP, suitable for scenarios where fine-grained time control is required. Through it, it can realize precise rhythm control of tasks such as file processing and API calls, improving program stability and system load balancing. Using this function rationally can make your PHP program run smoother and avoid the potential risks brought by too fast operations.