Skip to content

Commit ccb7c81

Browse files
Merge pull request #25 from utopia-php/feat-loop-delay-and-accuracy
Introducing loop deal and accuracy.
2 parents 3d37482 + 31a20c6 commit ccb7c81

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

src/CLI/Console.php

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -195,17 +195,27 @@ public static function isInteractive(): bool
195195

196196
/**
197197
* @param callable $callback
198-
* @param float $sleep // in seconds!
199-
* @param callable $onError
198+
* @param int $sleep // in seconds!
199+
* @param int $delay // in seconds!
200+
* @param callable|null $onError
201+
*
202+
* @throws \Exception
200203
*/
201-
public static function loop(callable $callback, $sleep = 1 /* seconds */, callable $onError = null): void
204+
public static function loop(callable $callback, int $sleep = 1 /* seconds */, int $delay = 0 /* seconds */, callable $onError = null): void
202205
{
203206
gc_enable();
204207

205208
$time = 0;
206209

210+
if ($delay > 0) {
211+
sleep($delay);
212+
}
213+
207214
while (! connection_aborted() || PHP_SAPI == 'cli') {
215+
$suspend = $sleep;
216+
208217
try {
218+
$execStart = \time();
209219
$callback();
210220
} catch (\Exception $e) {
211221
if ($onError != null) {
@@ -215,8 +225,11 @@ public static function loop(callable $callback, $sleep = 1 /* seconds */, callab
215225
}
216226
}
217227

218-
$intSeconds = intval($sleep);
219-
$microSeconds = ($sleep - $intSeconds) * 1000000;
228+
$execTotal = \time() - $execStart;
229+
$suspend = $suspend - $execTotal;
230+
231+
$intSeconds = intval($suspend);
232+
$microSeconds = ($suspend - $intSeconds) * 1000000;
220233

221234
if ($intSeconds > 0) {
222235
sleep($intSeconds);
@@ -226,7 +239,7 @@ public static function loop(callable $callback, $sleep = 1 /* seconds */, callab
226239
usleep($microSeconds);
227240
}
228241

229-
$time = $time + $sleep;
242+
$time = $time + $suspend;
230243

231244
if (PHP_SAPI == 'cli') {
232245
if ($time >= 60 * 5) { // Every 5 minutes

0 commit comments

Comments
 (0)