1 | <?php |
||
7 | class LoopedProcessRunner |
||
8 | { |
||
9 | /** @var LoopInterface */ |
||
10 | private $loop; |
||
11 | |||
12 | /** @var callable */ |
||
13 | private $process; |
||
14 | |||
15 | /** @var int */ |
||
16 | private $elapsedTime = 0; |
||
17 | |||
18 | /** @var int */ |
||
19 | private $startTime; |
||
20 | |||
21 | /** @var int|null */ |
||
22 | private $timeLimit; |
||
23 | |||
24 | /** @var int */ |
||
25 | private $interval = 1; |
||
26 | |||
27 | /** |
||
28 | * @param LoopInterface $loop |
||
29 | * @param callable $process function that returns a boolean to decide whether to go again immediately |
||
30 | */ |
||
31 | public function __construct(LoopInterface $loop, callable $process) |
||
36 | |||
37 | /** |
||
38 | * @param callable $process function that returns a boolean to decide whether to go again immediately |
||
39 | * |
||
40 | * @return self |
||
41 | */ |
||
42 | public function setProcess(callable $process): self |
||
48 | |||
49 | /** |
||
50 | * @param int $timeLimit in seconds |
||
51 | * |
||
52 | * @return self |
||
53 | */ |
||
54 | public function setTimeLimit(int $timeLimit): self |
||
60 | |||
61 | /** |
||
62 | * @param int $interval seconds to wait between runs that didn't process anything |
||
63 | * |
||
64 | * @return self |
||
65 | */ |
||
66 | public function setInterval(int $interval): self |
||
72 | |||
73 | /** |
||
74 | * run the callable process repeatedly, every second unless it returns true in which case more than once per second |
||
75 | * in the context of pulling from a Redis queue, we return true if we processed an item because that suggests that |
||
76 | * there may be more items to process, so we should try again immediately instead of waiting for the next call |
||
77 | * this should allow us to process many items very quickly whilst retaining low overheads |
||
78 | * it will keep the loop active until the given time limit, and then expire |
||
79 | */ |
||
80 | public function run() |
||
100 | |||
101 | private function updateElapsedTime() |
||
105 | |||
106 | private function hasExceededTimeLimit(): bool |
||
115 | |||
116 | private function notExceededTimeLimit(): bool |
||
120 | } |
||
121 |