|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace FondBot\Toolbelt\Commands; |
|
6
|
|
|
|
|
7
|
|
|
use FondBot\Contracts\Queue; |
|
8
|
|
|
use FondBot\Toolbelt\Command; |
|
9
|
|
|
use Symfony\Component\Console\Input\InputOption; |
|
10
|
|
|
|
|
11
|
|
|
class QueueWorker extends Command |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var float */ |
|
14
|
|
|
private $startTime; |
|
15
|
|
|
/** @var int */ |
|
16
|
|
|
private $jobsHandled; |
|
17
|
|
|
|
|
18
|
2 |
|
protected function configure(): void |
|
19
|
|
|
{ |
|
20
|
|
|
$this |
|
21
|
2 |
|
->setName('queue:worker') |
|
22
|
2 |
|
->setDescription('Run queue worker') |
|
23
|
2 |
|
->addOption('timeout', 't', InputOption::VALUE_OPTIONAL, 'The number of seconds worker will run.') |
|
24
|
2 |
|
->addOption('jobs', 'j', InputOption::VALUE_OPTIONAL, 'The number of jobs worker will process.'); |
|
25
|
2 |
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Handle command. |
|
29
|
|
|
* |
|
30
|
|
|
* @throws \Psr\Container\ContainerExceptionInterface |
|
31
|
|
|
* @throws \Symfony\Component\Console\Exception\InvalidArgumentException |
|
32
|
|
|
*/ |
|
33
|
1 |
|
public function handle(): void |
|
34
|
|
|
{ |
|
35
|
1 |
|
$this->startTime = microtime(true); |
|
36
|
1 |
|
$this->jobsHandled = 0; |
|
37
|
|
|
|
|
38
|
|
|
/** @var Queue $queue */ |
|
39
|
1 |
|
$queue = resolve(Queue::class); |
|
40
|
|
|
|
|
41
|
1 |
|
$this->info('Worker started...'); |
|
42
|
|
|
|
|
43
|
1 |
|
while (true) { |
|
44
|
1 |
|
$job = $queue->next(); |
|
45
|
|
|
|
|
46
|
1 |
|
if ($job === null) { |
|
47
|
1 |
|
continue; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
1 |
|
$this->line('Job: '.get_class($job)); |
|
51
|
|
|
|
|
52
|
1 |
|
$driver = $job->driver; |
|
53
|
1 |
|
$command = $job->command; |
|
54
|
|
|
|
|
55
|
1 |
|
$driver->handle($command); |
|
56
|
|
|
|
|
57
|
1 |
|
if ($this->isTimeout() || $this->handledJobsInLimit()) { |
|
58
|
1 |
|
break; |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
1 |
|
} |
|
62
|
|
|
|
|
63
|
1 |
|
private function isTimeout(): bool |
|
64
|
|
|
{ |
|
65
|
1 |
|
$timeout = $this->getOption('timeout') ?? 60; |
|
66
|
|
|
|
|
67
|
1 |
|
return microtime(true) - $this->startTime > $timeout; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
1 |
|
private function handledJobsInLimit(): bool |
|
71
|
|
|
{ |
|
72
|
1 |
|
$this->jobsHandled++; |
|
73
|
1 |
|
$limit = (int) $this->getOption('jobs'); |
|
74
|
|
|
|
|
75
|
1 |
|
return $limit <= 0 || $this->jobsHandled >= $limit; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|