Skip to content

Commit d753a41

Browse files
Update Loop, don't sleep any longer than there is time remaining
1 parent f121fef commit d753a41

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

classes/util/Loop.php

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class Loop
2323
/**
2424
* @var bool True while code should be repeated.
2525
*/
26-
private $looping;
26+
private $looping = false;
2727

2828
/**
2929
* Sets the timeout.
@@ -68,17 +68,33 @@ public function end()
6868
public function execute(callable $code)
6969
{
7070
$this->looping = true;
71-
$minWait = 100;
72-
$timeout = microtime(true) + $this->timeout;
71+
$minWait = 100; // microseconds
72+
$timeout = microtime(true) + $this->timeout; // At this time, the lock will time out.
73+
$result = null;
74+
7375
for ($i = 0; $this->looping && microtime(true) < $timeout; $i++) {
7476
$result = call_user_func($code);
7577
if (!$this->looping) {
7678
break;
7779
}
78-
$min = $minWait * pow(2, $i);
80+
81+
$min = $minWait * 2 ** $i;
7982
$max = $min * 2;
80-
$usleep = \random_int($min, $max);
81-
83+
84+
/*
85+
* Calculate max time remaining, don't sleep any longer than that.
86+
*/
87+
$usec_remaining = intval(($timeout - microtime(true)) * 1e6);
88+
89+
if ($usec_remaining <= 0) {
90+
/*
91+
* We've ran out of time.
92+
*/
93+
throw new TimeoutException("Timeout of $this->timeout seconds exceeded.");
94+
}
95+
96+
$usleep = min($usec_remaining, \random_int($min, $max));
97+
8298
usleep($usleep);
8399
}
84100

0 commit comments

Comments
 (0)