forked from pavlokomarov/roach-php-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayRequestScheduler.php
More file actions
79 lines (60 loc) · 1.65 KB
/
ArrayRequestScheduler.php
File metadata and controls
79 lines (60 loc) · 1.65 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
<?php
declare(strict_types=1);
/**
* Copyright (c) 2021 Kai Sassnowski
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* @see https://github.com/roach-php/roach
*/
namespace RoachPHP\Scheduling;
use DateInterval;
use DateTimeImmutable;
use RoachPHP\Http\Request;
use RoachPHP\Scheduling\Timing\ClockInterface;
final class ArrayRequestScheduler implements RequestSchedulerInterface
{
private int $batchSize = 25;
private int $delay = 0;
/**
* @var Request[]
*/
private array $requests = [];
private DateTimeImmutable $nextBatchReadyAt;
public function __construct(private ClockInterface $clock)
{
$this->nextBatchReadyAt = $this->clock->now();
}
public function schedule(Request $request): void
{
$this->requests[] = $request;
}
public function empty(): bool
{
return empty($this->requests);
}
/**
* @return Request[]
*/
public function nextRequests(): array
{
$this->clock->sleepUntil($this->nextBatchReadyAt);
$this->updateNextBatchTime();
return \array_splice($this->requests, 0, $this->batchSize);
}
public function setBatchSize(int $batchSize): RequestSchedulerInterface
{
$this->batchSize = $batchSize;
return $this;
}
public function setDelay(int $delay): RequestSchedulerInterface
{
$this->delay = $delay;
return $this;
}
private function updateNextBatchTime(): void
{
$this->nextBatchReadyAt = $this->clock->now()->add(new DateInterval("PT{$this->delay}S"));
}
}