forked from lstrojny/functional-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPoll.php
More file actions
60 lines (48 loc) · 1.45 KB
/
Poll.php
File metadata and controls
60 lines (48 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
/**
* @package Functional-php
* @author Lars Strojny <lstrojny@php.net>
* @copyright 2011-2021 Lars Strojny
* @license https://opensource.org/licenses/MIT MIT
* @link https://github.com/lstrojny/functional-php
*/
namespace Functional;
use AppendIterator;
use ArrayIterator;
use Functional\Exceptions\InvalidArgumentException;
use InfiniteIterator;
use Traversable;
/**
* Retry a callback until it returns a truthy value or the timeout (in microseconds) is reached
*
* @param callable $callback
* @param integer $timeout Timeout in microseconds
* @param Traversable|null $delaySequence Default: no delay between calls
* @throws InvalidArgumentException
* @return boolean
* @no-named-arguments
*/
function poll(callable $callback, $timeout, ?Traversable $delaySequence = null)
{
InvalidArgumentException::assertIntegerGreaterThanOrEqual($timeout, 0, __FUNCTION__, 2);
$retry = 0;
$delays = new AppendIterator();
if ($delaySequence) {
$delays->append(new InfiniteIterator($delaySequence));
}
$delays->append(new InfiniteIterator(new ArrayIterator([0])));
$limit = \microtime(true) + ($timeout / 100000);
foreach ($delays as $delay) {
$value = $callback($retry, $delay);
if ($value) {
return $value;
}
if (\microtime(true) > $limit) {
return false;
}
if ($delay > 0) {
\usleep($delay);
}
++$retry;
}
}