-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoop.php
More file actions
86 lines (74 loc) · 2.61 KB
/
Loop.php
File metadata and controls
86 lines (74 loc) · 2.61 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
declare(strict_types=1);
namespace Netlogix\JobQueue\FastRabbit;
use Neos\Flow\Annotations as Flow;
use Netlogix\JobQueue\Pool\Pool;
use PhpAmqpLib\Exception\AMQPTimeoutException;
use t3n\JobQueue\RabbitMQ\Queue\RabbitQueue;
use function count;
use function max;
#[Flow\Proxy(false)]
final class Loop
{
public const int SIX_HOURS_IN_SECONDS = 21600;
public function __construct(
/**
* The Queue to watch
*/
protected RabbitQueue $queue,
protected readonly Pool $poolObject,
/**
* Time in seconds after which the loop should exit
*/
protected readonly ?int $exitAfter
) {
}
public function runMessagesOnWorker(Worker $worker)
{
$this
->poolObject
->runLoop(function (Pool $pool) use ($worker) {
$worker->prepare();
$runDueJobs = $pool->eventLoop->addPeriodicTimer(
interval: 0.01,
callback: fn () => $this->runDueJob($pool, $worker)
);
if ($this->exitAfter) {
$pool->eventLoop->addTimer(
interval: max($this->exitAfter, 1),
callback: function () use ($pool, $runDueJobs) {
$pool->eventLoop->cancelTimer($runDueJobs);
$checkForPoolToClear = $pool->eventLoop->addPeriodicTimer(
interval: 1,
callback: function () use ($pool, &$checkForPoolToClear) {
if (count($pool) === 0) {
$pool->eventLoop->cancelTimer($checkForPoolToClear);
$pool->eventLoop->stop();
}
}
);
}
);
}
});
}
private function runDueJob(Pool $pool, Worker $worker): void
{
/**
* No parallel execution of multiple messages here, create multiple
* fast rabbit instances connected instead.
* Counting the running instances in the pool only prevents the
* pool from spawning too many workers.
*/
if (count($pool)) {
return;
}
try {
$message = $this->queue->waitAndReserve(10);
if ($message) {
$pool->eventLoop->futureTick(fn () => $worker->executeMessage($message));
}
} catch (AMQPTimeoutException $e) {
}
}
}