time limiter
1.0.0
一個小實用程式類,有助於限制腳本執行時間。
該類別通常在消耗大量時間的循環中使用。
// maximum time to execute one request
$ REQUEST_TIMEOUT_SEC = 5 ;
$ curlClient = new SomeCurlClient (); // just an example.
// shared hosting often has a limit. E.g. 30 seconds
$ maxExecutionTime = ini_get ( ' max_execution_time ' );
$ timeLimiter = new timelimiter TimeLimiter ( $ maxExecutionTime , $ REQUEST_TIMEOUT_SEC );
// check if there is time left to prevent 504 timeout
// recommended
foreach ( $ timeLimiter => $ timeLeft ){
$ result = $ curlClient -> doSomeHeavyJob ([
' timeout ' => $ REQUEST_TIMEOUT_SEC
]);
// handle the result
// ...
}
// or alternatively while loop might be used with respective Iterator calls.
while ( $ timeLimiter -> valid ()){
$ result = $ curlClient -> doSomeHeavyJob ([
' timeout ' => $ REQUEST_TIMEOUT_SEC
]);
$ timeLimiter -> next (); // must be called to adapt to long iterations
}
作為使用 Composer 的生產依賴項:
composer require morjodrom/time-limiter
作為僅開發案例的開發依賴項:
composer require --dev morjodrom/time-limiter
int $limitSeconds
- 處理秒數。 0 等於沒有限制。 ini_get('max_execution_time')
中的值可能是所需的選項。
[int $preliminaryTimeout] = DEFAULT_TIME_UP_SECONDS = 3
秒,在達到逾時之前停止初步執行。 $preliminaryTimeout
必須比循環中執行的最長理論操作稍大一些。因此,最後一個可能超過執行時間的有風險的操作被忽略。該類別追蹤每次迭代所花費的時間,以更新 $preliminaryTimeout 以等於最長的操作
[int|null $startTimestamp = $_SERVER['REQUEST_TIME']
。必須是自 Unix Epoch(1970 年 1 月 1 日 00:00:00 GMT)以來的時間戳,例如time()
呼叫。強烈鼓勵使用foreach
結構。透過正確的迭代器呼叫也可以進行原始while
迭代
current(): int
- 傳回逾時前剩餘的秒數valid(): bool
- 如果還有時間安全執行腳本則傳回next(): void
- 必須在完成迭代後呼叫以適應意外的長迭代
歡迎提問:https://github.com/Morjodrom/time-limiter/issues