Current Location: Home> Latest Articles> Use time_nanosleep to implement accurate task scheduler

Use time_nanosleep to implement accurate task scheduler

gitbox 2025-05-27

In web development, PHP is traditionally considered unsuitable for long-running processes or task scheduling systems. However, with enhanced support for CLI mode and the availability of some underlying functions such as time_nanosleep , PHP is actually capable of some lightweight but time-required scheduling tasks.

This article will introduce how to use time_nanosleep to build a simple but high-precision task scheduler to perform periodic tasks with millisecond or even microsecond precision.

1. Why use time_nanosleep

Conventional delay functions in PHP such as sleep() and usleep() support second and microsecond delays, respectively, but are not always accurate enough in actual operation, and the accuracy of usleep will be limited on some platforms.

In contrast, time_nanosleep provides nanosecond-level time control:

 bool time_nanosleep(int $seconds, int $nanoseconds): bool|array

It allows us to control the time of each scheduling cycle more granularly, thus achieving near real-time task execution.

2. Basic ideas for building schedulers

The core idea of ​​task scheduler is:

  1. Define a task list, each task comes with an execution cycle;

  2. Detect the current time in an infinite loop;

  3. Wait precisely for the next execution cycle;

  4. Run the task when the target time is reached.

3. Sample code

Here is an example implementation of a simple high-precision PHP scheduler:

 <?php

class TaskScheduler
{
    private array $tasks = [];

    public function addTask(callable $task, float $interval): void
    {
        $this->tasks[] = [
            'callback' => $task,
            'interval' => $interval, // unit:Second,Supported decimal
            'next_run' => microtime(true) + $interval
        ];
    }

    public function run(): void
    {
        while (true) {
            $now = microtime(true);

            foreach ($this->tasks as &$task) {
                if ($now >= $task['next_run']) {
                    call_user_func($task['callback']);
                    $task['next_run'] = $now + $task['interval'];
                }
            }

            // Accurate waiting 1 毫Second,avoidCPUToo high occupancy
            time_nanosleep(0, 1_000_000);
        }
    }
}

// Example:Every0.5Second输出一次时间戳
$scheduler = new TaskScheduler();

$scheduler->addTask(function () {
    echo "Task execution time:" . date('Y-m-d H:i:s.u') . PHP_EOL;
}, 0.5);

// Example:Every2Second执行一次Simulation request
$scheduler->addTask(function () {
    $url = "https://gitbox.net/api/ping";
    echo "Requesting $url" . PHP_EOL;
    // You can use it in actual scenarios curl or file_get_contents Simulation request
}, 2.0);

// Start the scheduler
$scheduler->run();

4. Things to note

  1. CPU occupancy : Since the scheduler is in an infinite loop, it is recommended to use functions such as time_nanosleep to reduce CPU occupancy.

  2. Error accumulation problem : In this example, the method of setting next_run is used to "start from the current time + cycle" to better control error accumulation.

  3. Exception handling : In the real environment, it is recommended to add try-catch to prevent a task from interrupting the scheduler's operation.

  4. Task isolation : If a task takes too long, it may affect the execution of other tasks. It can be further optimized for multi-process or use pcntl_fork to implement parallelism.

5. Application scenarios

  • Accurately controlled automatic data synchronization

  • Send messages at a time in microseconds (such as IoT)

  • Build a PHP local daemon or polling service

Conclusion

Although PHP is not designed for system-level scheduling, through functions such as time_nanosleep , we can still build a lightweight task scheduler with high precision and stable operation. Suitable for small applications or script tasks that require high real-time capabilities but are not suitable for introducing complex toolchains. In the future, combined with expansions such as coroutines and Swooles, PHP's timing scheduling capabilities still have more room to improve.