-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorker.php
More file actions
63 lines (48 loc) · 1.43 KB
/
Worker.php
File metadata and controls
63 lines (48 loc) · 1.43 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
<?php
declare(strict_types=1);
namespace LogadApp\Queue;
use Throwable;
class Worker
{
private int $sleep = 1;
private int $memoryLimit;
public function __construct(int $memoryLimitMB = 128)
{
$this->memoryLimit = $memoryLimitMB * 1024 * 1024;
}
/**
* Start the worker
*/
public function work(string $queue = 'default', callable $logger = null): void
{
$logger = $logger ?: function($message) {
echo $message . PHP_EOL;
};
$logger("Starting worker for queue: {$queue}");
while (true) {
if ($this->isMemoryExceeded()) {
$logger("Memory limit exceeded. Stopping..");
break;
}
$this->processNextJob($queue, $logger);
sleep($this->sleep);
}
}
protected function processNextJob(string $queue, callable $logger): void
{
$job = Queue::next($queue);
if (!$job) return;
$attempts = $job->getAttempts() + 1;
$logger("Processing job ID: {$job->getId()}, Attempt: {$attempts}");
try {
$job->process();
$logger("Job completed successfully");
} catch (Throwable $e) {
$logger("Job failed with error: {$e->getMessage()}");
}
}
private function isMemoryExceeded(): bool
{
return memory_get_usage(true) >= $this->memoryLimit;
}
}