void set_time_limit(int $seconds)
0 表示無限制php.ini max_execution_timesafe_mode = On 時函數失效 (PHP 5.4+ 已移除安全模式)<?php // php.ini: max_execution_time = 30 set_time_limit(20); // 重置計時器,剩餘 20 秒 sleep(10); // 經過 10 秒 set_time_limit(30); // 再次重置,剩餘 30 秒 (非 20+30) // 總共可執行 10 + 30 = 40 秒 ?>
| 操作類型 | 是否計入限制 | 說明 |
|---|---|---|
| PHP 程式碼執行 | 是 | CPU 運算、迴圈、函數呼叫 |
| system()/exec() 系統呼叫 | 否 | 外部程式執行時間不計入 |
| 資料庫查詢等待 | 否 | 等待 MySQL/PostgreSQL 回應 |
| 檔案/網路 IO 等待 | 否 | fread、curl、fsockopen 等待時間 |
| sleep()/usleep() | 是 | 睡眠時間計入 (Windows 除外) |
<?php
// 1. 長時間批次處理
set_time_limit(0); // 無限制
foreach ($largeDataset as $item) {
processItem($item);
// 定期釋放記憶體
if ($count++ % 1000 === 0) gc_collect_cycles();
}
// 2. 分段延長 (避免無限循環掛死)
function longTask() {
$maxSegments = 10;
$segmentTime = 30; // 每段 30 秒
for ($i = 0; $i < $maxSegments; $i++) {
set_time_limit($segmentTime);
doSegmentWork($i);
}
}
// 3. 命令列腳本 (CLI) 預設無限制
// php.ini: max_execution_time = 0 (CLI SAPI)
// Web 環境下才需手動調整
?>
<?php
// 腳本即將超時時執行清理
register_shutdown_function(function () {
$error = error_get_last();
if ($error && $error['type'] === E_ERROR) {
// 記錄超時錯誤、釋放鎖、發送告警
error_log("Script timeout: " . $error['message']);
}
});
// 模擬長時間任務
set_time_limit(5);
sleep(10); // 這裡會觸發 Fatal Error 後執行 shutdown function
?>
pcntl_fork 或 Swoole 異步處理set_time_limit(300) 定期重置善用 set_time_limit 控制執行邊界,配合分批處理模式,平衡功能完整性與系統穩定性。