隊列(Queue)遵循 FIFO (First In First Out) 原則,如同排隊買票。SPL 提供 SplQueue 基於雙向鏈表實現。
<?php
$queue = new SplQueue();
// 設置迭代模式:FIFO + 迭代後刪除
$queue->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);
// 入隊
$queue->enqueue('task-1');
$queue->enqueue('task-2');
$queue->enqueue('task-3');
// 出隊
echo $queue->dequeue() . "\n"; // task-1
// 迭代(消耗隊列)
foreach ($queue as $task) {
echo "Processing: $task\n";
}
// 隊列現為空
| 特性 | SplQueue (隊列) | SplStack (堆疊) |
|---|---|---|
| 順序 | FIFO (先進先出) | LIFO (後進先出) |
| 插入 | enqueue() / push() | push() |
| 移除 | dequeue() / shift() | pop() |
| IteratorMode | IT_MODE_FIFO | IT_MODE_LIFO |
| 應用 | 任務隊列、BFS、緩衝 | 遞迴模擬、DFS、撤銷操作 |
基於最大堆實現,每個元素關聯優先級數值,優先級高者先出隊。
<?php
$pq = new SplPriorityQueue();
// 插入:insert(value, priority)
$pq->insert('low priority task', 1);
$pq->insert('high priority task', 10);
$pq->insert('medium task', 5);
// 設置提取模式
$pq->setExtractFlags(SplPriorityQueue::EXTR_DATA); // 僅值
// SplPriorityQueue::EXTR_PRIORITY // 僅優先級
// SplPriorityQueue::EXTR_BOTH // ['data'=>..., 'priority'=>...]
// 提取
while ($pq->valid()) {
echo $pq->current() . " (priority: " . $pq->getPriority() . ")\n";
$pq->next();
}
// 輸出: high priority task (10) → medium task (5) → low priority task (1)
<?php
class TaskScheduler {
private $queue;
private $running = false;
public function __construct() {
$this->queue = new SplPriorityQueue();
$this->queue->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
}
public function addTask($task, $priority = 0, $delay = 0) {
// 支援延遲執行(簡易實現)
$entry = array(
'task' => $task,
'execute_at' => microtime(true) + $delay,
'attempts' => 0,
'max_attempts' => 3
);
$this->queue->insert($entry, $priority);
}
public function run() {
$this->running = true;
while ($this->running && !$this->queue->isEmpty()) {
$this->queue->top(); // 刷新 valid()
if (!$this->queue->valid()) break;
$entry = $this->queue->current();
$now = microtime(true);
if ($entry['execute_at'] > $now) {
// 尚未到執行時間,短暫休眠
usleep(10000); // 10ms
continue;
}
$this->queue->next(); // 移除當前
try {
$result = call_user_func($entry['task']);
echo "Task succeeded\n";
} catch (Exception $e) {
$entry['attempts']++;
if ($entry['attempts'] < $entry['max_attempts']) {
// 重試:降低優先級、延遲退避
$entry['execute_at'] = $now + pow(2, $entry['attempts']);
$this->queue->insert($entry, $entry['priority'] - 1);
echo "Task failed, retry {$entry['attempts']}\n";
} else {
echo "Task failed permanently: " . $e->getMessage() . "\n";
}
}
}
}
public function stop() { $this->running = false; }
}
// 使用
$scheduler = new TaskScheduler();
$scheduler->addTask(function() { echo "Send email\n"; }, 5);
$scheduler->addTask(function() { echo "Backup DB\n"; }, 10, 2); // 2秒後執行
$scheduler->addTask(function() { echo "Cleanup logs\n"; }, 1);
$scheduler->run();
<?php
// 簡易事件循環
class EventLoop {
private $timers = array(); // [time => [callbacks]]
private $queue;
public function __construct() {
$this->queue = new SplQueue();
}
public function addTimer($interval, $callback, $periodic = false) {
$id = spl_object_hash($callback);
$this->timers[$id] = array(
'next' => microtime(true) + $interval,
'interval' => $interval,
'callback' => $callback,
'periodic' => $periodic
);
}
public function run() {
while (true) {
$now = microtime(true);
// 處理定時器
foreach ($this->timers as $id => &$timer) {
if ($now >= $timer['next']) {
call_user_func($timer['callback']);
if ($timer['periodic']) {
$timer['next'] = $now + $timer['interval'];
} else {
unset($this->timers[$id]);
}
}
}
// 處理隊列任務
if (!$this->queue->isEmpty()) {
$task = $this->queue->dequeue();
call_user_func($task);
}
// 避免佔用 CPU
usleep(1000);
}
}
public function enqueue($task) {
$this->queue->enqueue($task);
}
}
foreach($queue) 會清空隊列(IT_MODE_DELETE 預設)insert() 優先級為整數/浮點數,非 Comparable 介面SPL 隊列族提供標準庫級數據結構,適合中等規模內存內任務調度,大規模分散式場景請使用專用消息隊列。