利用 $_SESSION 記錄總任務數與已完成數,每次請求遞減計數器,計算百分比回傳給前端輪詢顯示。
<?php
session_start();
$totalTasks = 21; // 總任務數
// 初始化
if (!isset($_SESSION['remaining'])) {
$_SESSION['remaining'] = $totalTasks;
}
// 取得並遞減剩餘任務
$remaining = $_SESSION['remaining']--;
$completed = $totalTasks - $remaining;
$percent = $totalTasks > 0 ? round(($completed / $totalTasks) * 100) : 100;
// 輸出 JSON 供前端 AJAX 輪詢
header('Content-Type: application/json');
echo json_encode([
'remaining' => max(0, $remaining),
'completed' => $completed,
'total' => $totalTasks,
'percent' => min(100, $percent),
'finished' => $remaining <= 0
]);
// 實際業務邏輯應在這裡執行一個任務單元
// 例如:處理一筆訂單、發送一封郵件、轉碼一段影片
?>
<div id="progress">進度: <span id="pct">0%</span></div>
<div id="bar" style="width:300px;height:20px;border:1px solid #ccc;">
<div id="fill" style="width:0%;height:100%;background:#4caf50;"></div>
</div>
<script>
function poll() {
fetch('progress.php')
.then(r => r.json())
.then(d => {
document.getElementById('pct').textContent = d.percent + '%';
document.getElementById('fill').style.width = d.percent + '%';
if (!d.finished) {
setTimeout(poll, 500); // 0.5 秒輪詢
} else {
alert('任務完成!');
}
});
}
poll();
</script>
| 問題 | 改進方案 |
|---|---|
| Session 鎖導致併發阻塞 | 用 session_write_close() 盡早釋放鎖,或改用 Redis 計數器 |
| 多伺服器 Session 不共享 | 集中式 Session(Redis/Memcached)或資料庫 |
| 任務中斷無法恢復 | 資料庫記錄任務狀態、進度、重試機制 |
| 長任務超時 | 拆分為微任務、使用隊列(Redis/RabbitMQ)+ Worker |
job_id → {total, done, status}