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