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

Skip to content

Commit 3dbb65f

Browse files
committed
[Scheduler] Proposal - initial structure for Symfony Scheduler documentation
1 parent 827744b commit 3dbb65f

File tree

3 files changed

+326
-0
lines changed

3 files changed

+326
-0
lines changed
89.3 KB
Loading
Loading

scheduler.rst

Lines changed: 326 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,326 @@
1+
Scheduler
2+
=========
3+
4+
.. versionadded:: 6.3
5+
6+
The Scheduler component was introduced in Symfony 6.3
7+
8+
The Symfony Scheduler is a powerful and flexible component designed to manage tasks scheduling within your PHP application.
9+
10+
This document focuses on using the Scheduler component in the context of a full stack Symfony application.
11+
12+
Installation
13+
------------
14+
15+
In applications using :ref:`Symfony Flex <symfony-flex>`, run this command to
16+
install the scheduler component:
17+
18+
.. code-block:: terminal
19+
20+
$ composer require symfony/scheduler
21+
22+
Debugging the Schedule
23+
~~~~~~~~~~~~~~~~~~~~~~
24+
25+
The ``debug:scheduler`` command provides a list of schedules along with their recurring messages.
26+
27+
You can narrow down the list to a specific schedule, or even specify a date to determine the next run date using the ``--date`` option.
28+
Additionally, you have the option to display terminated recurring messages using the ``--all`` option.
29+
30+
.. code-block:: terminal
31+
32+
$ php bin/console debug:scheduler
33+
34+
Scheduler
35+
=========
36+
37+
default
38+
-------
39+
40+
------------------- ------------------------- ----------------------
41+
Trigger Provider Next Run
42+
------------------- ------------------------- ----------------------
43+
every 2 days App\Messenger\Foo(0:17..) Sun, 03 Dec 2023 ...
44+
15 4 */3 * * App\Messenger\Foo(0:17..) Mon, 18 Dec 2023 ...
45+
-------------------- -------------------------- ---------------------
46+
47+
Introduction to the case
48+
------------------------
49+
50+
Embarking on a task is one thing, but often, the need to repeat that task looms large.
51+
While one could resort to issuing commands and scheduling them with cron jobs, this approach involves external tools and additional configuration.
52+
53+
The Scheduler component emerges as a solution, allowing you to retain control, configuration, and maintenance of task scheduling within our PHP application.
54+
55+
At its core, the principle is straightforward: a task, considered as a message needs to be managed by a service, and this cycle must be repeated.
56+
Does this sound familiar? Think :doc:`Symfony Messenger docs </components/messenger>`.
57+
58+
But while the system of Messenger proves very useful in various scenarios, there are instances where its capabilities
59+
fall short, particularly when dealing with repetitive tasks at regular intervals.
60+
61+
Let's dive into a practical example within the context of a sales company.
62+
63+
Imagine the company's goal is to send diverse sales reports to customers based on the specific reports each customer chooses to receive.
64+
In constructing the schedule for this scenario, the following steps are taken:
65+
66+
#. Iterate over reports stored in the database and create a recurring task for each report, considering its unique properties. This task, however, should not be generated during holiday periods.
67+
68+
#. Furthermore, you encounter another critical task that needs scheduling: the periodic cleanup of outdated files that are no longer relevant.
69+
70+
On the basis of a case study in the context of a full stack Symfony application, let's dive in and explore how you can set up your system.
71+
72+
Symfony Scheduler basics
73+
------------------------
74+
75+
Differences and parallels between Messenger and Scheduler
76+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
77+
78+
The primary goal is to generate and process reports generation while also handling the removal of outdated reports at specified intervals.
79+
80+
As mentioned, this component, even if it's an independent component, it draws its foundation and inspiration from the Messenger component.
81+
82+
On one hand, it adopts well-established concepts from Messenger (such as message, handler, bus, transport, etc.).
83+
For example, the task of creating a report is considered as a message that will be directed, and processed by the corresponding handler.
84+
85+
However, unlike Messenger, the messages will not be dispatched in the first instance. Instead, the aim is to create them based on a predefined frequency.
86+
87+
This is where the specific transport in Scheduler, known as the :class:`Symfony\\Component\\Scheduler\\Messenger\\SchedulerTransport`, plays a crucial role.
88+
The transport autonomously generates directly various messages according to the assigned frequencies.
89+
90+
From (Messenger cycle):
91+
92+
.. image:: /_images/components/messenger/basic_cycle.png
93+
:alt: Symfony Messenger basic cycle
94+
95+
To (Scheduler cycle):
96+
97+
.. image:: /_images/components/scheduler/scheduler_cycle.png
98+
:alt: Symfony Scheduler basic cycle
99+
100+
In essence, it is crucial to precisely define the message to be conveyed and processed. In Scheduler, the concept of a message takes on a very particular characteristic;
101+
it should be recurrent: It's a :class:`Symfony\\Component\\Scheduler\\RecurringMessage`.
102+
103+
Clarifying the need to define and attach RecurringMessages to a Schedule
104+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
105+
106+
In order to generate various messages based on their defined frequencies, configuration is necessary.
107+
The heart of the scheduling process and its configuration resides in a class that must extend the :class:`Symfony\\Component\\Scheduler\\ScheduleProviderInterface`.
108+
109+
The purpose of this provider is to return a schedule through the method :method:`Symfony\\Component\\Scheduler\\ScheduleProviderInterface::getMethod` containing your different recurringMessages.
110+
111+
The :class:`Symfony\\Component\\Scheduler\\Attribute\\AsSchedule` attribute, which by default references the ``default`` named schedule, allows you to register on a particular schedule::
112+
113+
// src/Scheduler/MyScheduleProvider.php
114+
namespace App\Scheduler;
115+
116+
class MyScheduleProvider implements ScheduleProviderInterface
117+
{
118+
public function getSchedule(): Schedule
119+
{
120+
// ...
121+
}
122+
}
123+
124+
.. tip::
125+
126+
This becomes important when initiating the ``messenger:consume`` command, especially when specifying one or more specific transports.
127+
In Scheduler, the transport is named ``scheduler_nameofyourschedule``.
128+
129+
.. tip::
130+
131+
It is a good practice to memoize your schedule to prevent unnecessary reconstruction if the ``getSchedule`` method is checked by another service or internally within Symfony
132+
133+
134+
The Concept of RecurringMessage in Scheduler
135+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
136+
137+
A message associated with a Trigger
138+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
139+
140+
First and foremost, a RecurringMessage is a message that will be associated with a trigger.
141+
142+
The trigger is what allows configuring the recurrence frequency of your message. Several options are available to us:
143+
144+
#. It can be a cron expression trigger:
145+
146+
.. configuration-block::
147+
148+
.. code-block:: php
149+
150+
RecurringMessage::cron(‘* * * * *’, new Message());
151+
152+
.. tip::
153+
154+
`dragonmantank/cron-expression`_ is required to use the cron expression trigger.
155+
156+
Also, `crontab_helper`_ is a good tool if you need help to construct/understand cron expressions
157+
158+
.. tip::
159+
160+
It's possible to add and define a timezone as a 3rd argument
161+
162+
#. It can be a periodicalTrigger through various frequency formats (string / integer / DateInterval)
163+
164+
.. configuration-block::
165+
166+
.. code-block:: php
167+
168+
RecurringMessage::every('10 seconds', new Message());
169+
RecurringMessage::every('3 weeks', new Message());
170+
RecurringMessage::every('first Monday of next month', new Message());
171+
172+
$from = new \DateTimeImmutable('13:47', new \DateTimeZone('Europe/Paris'));
173+
$until = '2023-06-12';
174+
RecurringMessage::every('first Monday of next month', new Message(), $from, $until);
175+
176+
#. It can be a custom trigger implementing :class:`Symfony\\Component\\Scheduler\\TriggerInterface`
177+
178+
If you go back to your scenario regarding reports generation based on your customer preferences.
179+
If the basic frequency is set to a daily basis, you will need to implement a custom trigger due to the specific requirement of not generating reports during public holiday periods::
180+
181+
// src/Scheduler/Trigger/NewUserWelcomeEmailHandler.php
182+
namespace App\Scheduler\Trigger;
183+
184+
class ExcludeHolidaysTrigger implements TriggerInterface
185+
{
186+
public function __construct(private TriggerInterface $inner)
187+
{
188+
}
189+
190+
public function __toString(): string
191+
{
192+
return $this->inner.' (except holidays)';
193+
}
194+
195+
public function getNextRunDate(\DateTimeImmutable $run): ?\DateTimeImmutable
196+
{
197+
if (!$nextRun = $this->inner->getNextRunDate($run)) {
198+
return null;
199+
}
200+
201+
while (!$this->isHoliday($nextRun) { // loop until you get the next run date that is not a holiday
202+
$nextRun = $this->inner->getNextRunDate($nextRun);
203+
}
204+
205+
return $nextRun;
206+
}
207+
208+
private function isHoliday(\DateTimeImmutable $timestamp): bool
209+
{
210+
// app specific logic to determine if $timestamp is on a holiday
211+
// returns true if holiday, false otherwise
212+
}
213+
}
214+
215+
Then, you would have to define your RecurringMessage
216+
217+
.. configuration-block::
218+
219+
.. code-block:: php
220+
221+
RecurringMessage::trigger(
222+
new ExcludeHolidaysTrigger( // your custom trigger wrapper
223+
CronExpressionTrigger::fromSpec('@daily'),
224+
),
225+
new SendDailySalesReports(),
226+
);
227+
228+
The RecurringMessages must be attached to a Schedule::
229+
230+
// src/Scheduler/MyScheduleProvider.php
231+
namespace App\Scheduler;
232+
233+
#[AsSchedule('uptoyou')]
234+
class MyScheduleProvider implements ScheduleProviderInterface
235+
{
236+
public function getSchedule(): Schedule
237+
{
238+
return $this->schedule ??= (new Schedule())
239+
->with(
240+
RecurringMessage::trigger(
241+
new ExcludeHolidaysTrigger( // your custom trigger wrapper
242+
CronExpressionTrigger::fromSpec('@daily'),
243+
),
244+
new SendDailySalesReports()),
245+
RecurringMessage::cron(‘3 8 * * 1’, new CleanUpOldSalesReport())
246+
247+
);
248+
}
249+
}
250+
251+
So, this RecurringMessage will encompass both the trigger, defining the generation frequency of the message, and the message itself, the one to be processed by a specific handler.
252+
But what is interesting to know is that it also provides you with the ability to generate your message(s) dynamically.
253+
254+
Efficient management with Symfony Scheduler
255+
-------------------------------------------
256+
257+
However, if your worker becomes idle, since the messages from your schedule are generated on-the-fly by the schedulerTransport,
258+
they won't be generated during this idle period.
259+
260+
While this might not pose a problem in certain situations, consider the impact for your sales company if a report is missed.
261+
262+
In this case, the scheduler has a feature that allows you to remember the last execution date of a message.
263+
So, when it wakes up again, it looks at all the dates and can catch up on what it missed.
264+
265+
This is where the ``stateful`` option comes into play. This option helps you remember where you left off, which is super handy for those moments when the worker is idle and you need to catch up::
266+
267+
// src/Scheduler/MyScheduleProvider.php
268+
namespace App\Scheduler;
269+
270+
class MyScheduleProvider implements ScheduleProviderInterface
271+
{
272+
public function getSchedule(): Schedule
273+
{
274+
$this->removeOldReports = RecurringMessage::cron(‘3 8 * * 1’, new CleanUpOldSalesReport());
275+
276+
return $this->schedule ??= (new Schedule())
277+
->with(
278+
// ...
279+
);
280+
->stateful($this->cache)
281+
}
282+
}
283+
284+
To scale your schedules more effectively, you can use multiple workers.
285+
In such cases, a good practice is to add a lock for some job concurrency optimization. It helps preventing the processing of a task from being duplicated::
286+
287+
// src/Scheduler/MyScheduleProvider.php
288+
namespace App\Scheduler;
289+
290+
class MyScheduleProvider implements ScheduleProviderInterface
291+
{
292+
public function getSchedule(): Schedule
293+
{
294+
$this->removeOldReports = RecurringMessage::cron(‘3 8 * * 1’, new CleanUpOldSalesReport());
295+
296+
return $this->schedule ??= (new Schedule())
297+
->with(
298+
// ...
299+
);
300+
->lock($this->lockFactory->createLock(‘my-lock’)
301+
}
302+
}
303+
304+
.. tip::
305+
306+
The processing time of a message matters.
307+
If it takes a long time, all subsequent message processing may be delayed. So, it's a good practice to anticipate this and plan for frequencies greater than the processing time of a message.
308+
309+
Additionally, for better scaling of your schedules, you have the option to wrap your message in a :class:`Symfony\\Component\\Messenger\\Message\\RedispatchMessage`.
310+
This allows you to specify a transport on which your message will be redispatched before being further redispatched to its corresponding handler::
311+
312+
// src/Scheduler/MyScheduleProvider.php
313+
namespace App\Scheduler;
314+
315+
class MyScheduleProvider implements ScheduleProviderInterface
316+
{
317+
public function getSchedule(): Schedule
318+
{
319+
return $this->schedule ??= (new Schedule())
320+
->with(RecurringMessage::every('5 seconds’), new RedispatchMessage(new Message(), ‘async’))
321+
);
322+
}
323+
}
324+
325+
.. _dragonmantank/cron-expression: https://packagist.org/packages/dragonmantank/cron-expression
326+
.. _crontab_helper: https://crontab.guru/

0 commit comments

Comments
 (0)