Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit edb1550

Browse files
committed
[Scheduler] Add a simple Scheduler class for when the component is used standalone
1 parent 5fbf9be commit edb1550

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Scheduler;
13+
14+
use Symfony\Component\Clock\Clock;
15+
use Symfony\Component\Clock\ClockInterface;
16+
use Symfony\Component\Scheduler\Generator\MessageGenerator;
17+
18+
/**
19+
* @experimental
20+
*/
21+
final class Scheduler
22+
{
23+
/**
24+
* @var array<MessageGenerator>
25+
*/
26+
private array $generators = [];
27+
private int $index = 0;
28+
private bool $shouldStop = false;
29+
30+
/**
31+
* @param iterable<Schedule> $schedules
32+
*/
33+
public function __construct(
34+
private array $handlers,
35+
array $schedules,
36+
private ClockInterface $clock = new Clock(),
37+
) {
38+
foreach ($schedules as $schedule) {
39+
$this->addSchedule($schedule);
40+
}
41+
}
42+
43+
public function addSchedule(Schedule $schedule): void
44+
{
45+
$this->addMessageGenerator(new MessageGenerator($schedule, 'schedule_'.$this->index++, $this->clock));
46+
}
47+
48+
public function addMessageGenerator(MessageGenerator $generator): void
49+
{
50+
$this->generators[] = $generator;
51+
}
52+
53+
/**
54+
* Schedules messages.
55+
*
56+
* Valid options are:
57+
* * sleep (default: 1000000): Time in microseconds to sleep after no messages are found
58+
*/
59+
public function run(array $options = []): void
60+
{
61+
$options += ['sleep' => 1e6];
62+
63+
while (!$this->shouldStop) {
64+
$start = $this->clock->now();
65+
66+
$ran = false;
67+
foreach ($this->generators as $generator) {
68+
foreach ($generator->getMessages() as $message) {
69+
$this->handlers[get_class($message)]($message);
70+
$ran = true;
71+
}
72+
}
73+
74+
if (!$ran) {
75+
if (0 < $sleep = (int) ($options['sleep'] - 1e6 * ($this->clock->now()->format('U.u') - $start->format('U.u')))) {
76+
$this->clock->sleep($sleep / 1e6);
77+
}
78+
}
79+
}
80+
}
81+
82+
public function stop(): void
83+
{
84+
$this->shouldStop = true;
85+
}
86+
}

0 commit comments

Comments
 (0)