|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace MGDigital\BusQue; |
|
4
|
|
|
|
|
5
|
|
|
class SchedulerWorker |
|
6
|
|
|
{ |
|
7
|
|
|
|
|
8
|
|
|
const DEFAULT_THROTTLE = 100; |
|
9
|
|
|
|
|
10
|
|
|
private $implementation; |
|
11
|
|
|
|
|
12
|
2 |
|
public function __construct(Implementation $implementation) |
|
13
|
|
|
{ |
|
14
|
2 |
|
$this->implementation = $implementation; |
|
15
|
2 |
|
} |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @param int|null $limit The maximum number of scheduled commands to queue. |
|
19
|
|
|
* @param int $throttle The maximum number of scheduled commands to receive at a time. |
|
20
|
|
|
* @param int|null $time The maximum amount of time in seconds to work. |
|
21
|
|
|
* @param int $uSleepTime The number of microseconds to usleep between each query to the scheduler. |
|
22
|
|
|
* @param \DateInterval|null $expiry The expiry interval for an overdue unqueued command. |
|
23
|
|
|
*/ |
|
24
|
1 |
|
public function work( |
|
25
|
|
|
int $limit = null, |
|
26
|
|
|
int $throttle = self::DEFAULT_THROTTLE, |
|
27
|
|
|
int $time = null, |
|
28
|
|
|
int $uSleepTime = 5000000, |
|
29
|
|
|
\DateInterval $expiry = null |
|
30
|
|
|
) { |
|
31
|
1 |
|
$stopwatchStart = time(); |
|
32
|
1 |
|
while ($limit === null || $limit > 0) { |
|
33
|
1 |
|
$queuedCount = $this->iterate($throttle, $expiry); |
|
34
|
1 |
|
if ($limit !== null) { |
|
35
|
1 |
|
$limit -= $queuedCount; |
|
36
|
1 |
|
if ($limit <= 0) { |
|
37
|
1 |
|
break; |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
if ($time !== null && (time() - $stopwatchStart >= $time)) { |
|
41
|
|
|
break; |
|
42
|
|
|
} |
|
43
|
|
|
usleep($uSleepTime); |
|
44
|
|
|
} |
|
45
|
1 |
|
} |
|
46
|
|
|
|
|
47
|
1 |
|
private function iterate(int $throttle, \DateInterval $expiry = null): int |
|
48
|
|
|
{ |
|
49
|
1 |
|
$count = 0; |
|
50
|
1 |
|
$now = $this->implementation->getClock()->getTime(); |
|
51
|
1 |
|
if ($expiry === null) { |
|
52
|
1 |
|
$start = null; |
|
53
|
|
|
} else { |
|
54
|
|
|
$start = new \DateTimeImmutable('@' . ($now->getTimestamp() - $expiry->s)); |
|
55
|
|
|
} |
|
56
|
1 |
|
$receivedCommands = $this->implementation->getSchedulerDriver() |
|
57
|
1 |
|
->receiveDueCommands($now, $throttle, $start); |
|
58
|
1 |
|
foreach ($receivedCommands as $command) { |
|
59
|
1 |
|
$this->handleReceivedCommand($command); |
|
60
|
1 |
|
$count++; |
|
61
|
|
|
} |
|
62
|
1 |
|
return $count; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
1 |
|
private function handleReceivedCommand(ReceivedScheduledCommand $command) |
|
66
|
|
|
{ |
|
67
|
1 |
|
$this->implementation->getQueueDriver() |
|
68
|
1 |
|
->queueCommand( |
|
69
|
1 |
|
$command->getQueueName(), |
|
70
|
1 |
|
$command->getId(), |
|
71
|
1 |
|
$command->getSerialized() |
|
72
|
|
|
); |
|
73
|
1 |
|
$this->implementation->getLogger()->debug('Scheduled command queued', compact('command')); |
|
74
|
1 |
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|