forked from eislambey/php-rsmq
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathQueueWorker.php
133 lines (116 loc) · 2.7 KB
/
QueueWorker.php
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
<?php declare(strict_types=1);
namespace AndrewBreksa\RSMQ;
/**
* Class QueueWorker
*
* @package AndrewBreksa\RSMQ
* @author Andrew Breksa <[email protected]>
*/
class QueueWorker
{
/**
* @var RSMQClientInterface
*/
protected $rsmq;
/**
* @var ExecutorInterface
*/
protected $executor;
/**
* @var string
*/
protected $queue;
/**
* @var WorkerSleepProvider
*/
protected $sleepProvider;
/**
* @var int
*/
protected $received = 0;
/**
* @var int
*/
protected $failed = 0;
/**
* @var int
*/
protected $successful = 0;
/**
* QueueWorker constructor.
*
* @param RSMQClientInterface $rsmq
* @param ExecutorInterface $executor
* @param WorkerSleepProvider $sleepProvider
* @param string $queue
*/
public function __construct(
RSMQClientInterface $rsmq,
ExecutorInterface $executor,
WorkerSleepProvider $sleepProvider,
string $queue
) {
$this->rsmq = $rsmq;
$this->executor = $executor;
$this->sleepProvider = $sleepProvider;
$this->queue = $queue;
}
/**
* @param bool $processOne
* @throws Exceptions\QueueNotFoundException
* @throws Exceptions\QueueParametersValidationException
*/
public function work(bool $processOne = false): void
{
while (true) {
$sleep = $this->sleepProvider->getSleep();
if ($sleep === null || $sleep < 0) {
break;
}
$message = $this->rsmq->receiveMessage($this->queue);
if (!($message instanceof Message)) {
sleep($sleep);
continue;
}
$this->received++;
$result = $this->executor->__invoke($message);
if ($result === true) {
$this->successful++;
$this->rsmq->deleteMessage($this->queue, $message->getId());
} else {
$this->failed++;
}
if ($processOne && $this->getProcessedCount() === 1) {
break;
}
}
}
/**
* @return int
*/
public function getProcessedCount(): int
{
return $this->successful + $this->failed;
}
/**
* @return int
*/
public function getReceived(): int
{
return $this->received;
}
/**
* @return int
*/
public function getFailed(): int
{
return $this->failed;
}
/**
* @return int
*/
public function getSuccessful(): int
{
return $this->successful;
}
}