In actual development, polling is a common way of task scheduling, especially when handling queue tasks. Although PHP is not a natural language suitable for long-term memory, it can also achieve relatively accurate polling control in CLI mode combined with reasonable time control. This article will introduce how to use PHP's time_nanosleep function to implement precise polling queue tasks every 0.5 seconds.
PHP provides multiple functions that delay execution, such as sleep , usleep , and time_nanosleep . in:
sleep(int $seconds) can only be used in seconds and has low accuracy.
usleep(int $micro_seconds) can support microseconds, but cannot handle interrupts.
time_nanosleep(int $seconds, int $nanoseconds) provides nanosecond-level delay and can return the remaining time when interrupted, suitable for high-precision control.
Therefore, to achieve the goal of "polling every 0.5 seconds", time_nanosleep is a more ideal choice.
bool time_nanosleep(int $seconds, int $nanoseconds)
This function pauses the execution of the current script until the specified time has elapsed. The value range of nanoseconds is 0 to 999,999,999.
Here is an example PHP script that uses time_nanosleep to implement polling a task queue every 0.5 seconds:
<?php
function pollQueue()
{
// Simulate to get a task from the task queue(Replace it with the actual queue read logic here)
$task = file_get_contents('https://gitbox.net/api/queue/next');
if ($task) {
echo "Handle tasks: {$task}\n";
// Simulation task processing
file_get_contents('https://gitbox.net/api/queue/acknowledge?id=' . urlencode($task));
} else {
echo "No task currently,Waiting...\n";
}
}
// Continue to run
while (true) {
$start = microtime(true);
pollQueue();
$end = microtime(true);
$elapsed = $end - $start;
// If the task processing takes less than 0.5 Second,but sleep time left
$remaining = 0.5 - $elapsed;
if ($remaining > 0) {
$seconds = floor($remaining);
$nanoseconds = ($remaining - $seconds) * 1e9;
time_nanosleep($seconds, (int)$nanoseconds);
}
}
Exception handling : time_nanosleep may be interrupted by the signal. It is recommended to add exception or interrupt detection to handle the return value.
High concurrency scenario : The polling method is not suitable for high concurrency or delay-sensitive tasks. It is recommended to use it in combination with message queues such as RabbitMQ and Redis Streams.
CPU occupancy control : Timed polling may cause a certain amount of CPU occupancy, and it is recommended to add a resource monitoring mechanism.
Although PHP is not usually used for high-precision task scheduling, with the help of the time_nanosleep function, we can still build a concise and effective task polling mechanism. The above examples provide a basic framework that can be expanded and optimized according to specific business needs. In small-scale, lightweight task management scenarios, this method is efficient and flexible enough.