Debian Codegraph @

docs/userguide/periodic-tasks.rst

raw
1 .. _guide-beat:
2
3 ================
4 Periodic Tasks
5 ================
6
7 .. contents::
8 :local:
9
10 Introduction
11 ============
12
13 :program:`celery beat` is a scheduler; It kicks off tasks at regular intervals,
14 that are then executed by available worker nodes in the cluster.
15
16 By default the entries are taken from the :setting:`beat_schedule` setting,
17 but custom stores can also be used, like storing the entries in a SQL database.
18
19 You have to ensure only a single scheduler is running for a schedule
20 at a time, otherwise you'd end up with duplicate tasks. Using
21 a centralized approach means the schedule doesn't have to be synchronized,
22 and the service can operate without using locks.
23
24 .. _beat-timezones:
25
26 Time Zones
27 ==========
28
29 The periodic task schedules uses the UTC time zone by default,
30 but you can change the time zone used using the :setting:`timezone`
31 setting.
32
33 An example time zone could be `Europe/London`:
34
35 .. code-block:: python
36
37 timezone = 'Europe/London'
38
39 This setting must be added to your app, either by configuring it directly
40 using (``app.conf.timezone = 'Europe/London'``), or by adding
41 it to your configuration module if you have set one up using
42 ``app.config_from_object``. See :ref:`celerytut-configuration` for
43 more information about configuration options.
44
45 The default scheduler (storing the schedule in the :file:`celerybeat-schedule`
46 file) will automatically detect that the time zone has changed, and so will
47 reset the schedule itself, but other schedulers may not be so smart (e.g., the
48 Django database scheduler, see below) and in that case you'll have to reset the
49 schedule manually.
50
51 .. admonition:: Django Users
52
53 Celery recommends and is compatible with the ``USE_TZ`` setting introduced
54 in Django 1.4.
55
56 For Django users the time zone specified in the ``TIME_ZONE`` setting
57 will be used, or you can specify a custom time zone for Celery alone
58 by using the :setting:`timezone` setting.
59
60 The database scheduler won't reset when timezone related settings
61 change, so you must do this manually:
62
63 .. code-block:: console
64
65 $ python manage.py shell
66 >>> from djcelery.models import PeriodicTask
67 >>> PeriodicTask.objects.update(last_run_at=None)
68
69 Django-Celery only supports Celery 4.0 and below, for Celery 4.0 and above, do as follow:
70
71 .. code-block:: console
72
73 $ python manage.py shell
74 >>> from django_celery_beat.models import PeriodicTask
75 >>> PeriodicTask.objects.update(last_run_at=None)
76
77 .. _beat-entries:
78
79 Entries
80 =======
81
82 To call a task periodically you have to add an entry to the
83 beat schedule list.
84
85 .. code-block:: python
86
87 from celery import Celery
88 from celery.schedules import crontab
89
90 app = Celery()
91
92 @app.on_after_configure.connect
93 def setup_periodic_tasks(sender: Celery, **kwargs):
94 # Calls test('hello') every 10 seconds.
95 sender.add_periodic_task(10.0, test.s('hello'), name='add every 10')
96
97 # Calls test('hello') every 30 seconds.
98 # It uses the same signature of previous task, an explicit name is
99 # defined to avoid this task replacing the previous one defined.
100 sender.add_periodic_task(30.0, test.s('hello'), name='add every 30')
101
102 # Calls test('world') every 30 seconds
103 sender.add_periodic_task(30.0, test.s('world'), expires=10)
104
105 # Executes every Monday morning at 7:30 a.m.
106 sender.add_periodic_task(
107 crontab(hour=7, minute=30, day_of_week=1),
108 test.s('Happy Mondays!'),
109 )
110
111 @app.task
112 def test(arg):
113 print(arg)
114
115 @app.task
116 def add(x, y):
117 z = x + y
118 print(z)
119
120
121
122 Setting these up from within the :data:`~@on_after_configure` handler means
123 that we'll not evaluate the app at module level when using ``test.s()``. Note that
124 :data:`~@on_after_configure` is sent after the app is set up, so tasks outside the
125 module where the app is declared (e.g. in a `tasks.py` file located by
126 :meth:`celery.Celery.autodiscover_tasks`) must use a later signal, such as
127 :data:`~@on_after_finalize`.
128
129 The :meth:`~@add_periodic_task` function will add the entry to the
130 :setting:`beat_schedule` setting behind the scenes, and the same setting
131 can also be used to set up periodic tasks manually:
132
133 Example: Run the `tasks.add` task every 30 seconds.
134
135 .. code-block:: python
136
137 app.conf.beat_schedule = {
138 'add-every-30-seconds': {
139 'task': 'tasks.add',
140 'schedule': 30.0,
141 'args': (16, 16)
142 },
143 }
144 app.conf.timezone = 'UTC'
145
146
147 .. note::
148
149 If you're wondering where these settings should go then
150 please see :ref:`celerytut-configuration`. You can either
151 set these options on your app directly or you can keep
152 a separate module for configuration.
153
154 If you want to use a single item tuple for `args`, don't forget
155 that the constructor is a comma, and not a pair of parentheses.
156
157 Using a :class:`~datetime.timedelta` for the schedule means the task will
158 be sent in 30 second intervals (the first task will be sent 30 seconds
159 after `celery beat` starts, and then every 30 seconds
160 after the last run).
161
162 A Crontab like schedule also exists, see the section on `Crontab schedules`_.
163
164 Like with :command:`cron`, the tasks may overlap if the first task doesn't complete
165 before the next. If that's a concern you should use a locking
166 strategy to ensure only one instance can run at a time (see for example
167 :ref:`cookbook-task-serial`).
168
169 .. _beat-entry-fields:
170
171 Available Fields
172 ----------------
173
174 * `task`
175
176 The name of the task to execute.
177
178 Task names are described in the :ref:`task-names` section of the User Guide.
179 Note that this is not the import path of the task, even though the default
180 naming pattern is built like it is.
181
182 * `schedule`
183
184 The frequency of execution.
185
186 This can be the number of seconds as an integer, a
187 :class:`~datetime.timedelta`, or a :class:`~celery.schedules.crontab`.
188 You can also define your own custom schedule types, by extending the
189 interface of :class:`~celery.schedules.schedule`.
190
191 * `args`
192
193 Positional arguments (:class:`list` or :class:`tuple`).
194
195 * `kwargs`
196
197 Keyword arguments (:class:`dict`).
198
199 * `options`
200
201 Execution options (:class:`dict`).
202
203 This can be any argument supported by
204 :meth:`~celery.app.task.Task.apply_async` --
205 `exchange`, `routing_key`, `expires`, and so on.
206
207 * `relative`
208
209 If `relative` is true :class:`~datetime.timedelta` schedules are scheduled
210 "by the clock." This means the frequency is rounded to the nearest
211 second, minute, hour or day depending on the period of the
212 :class:`~datetime.timedelta`.
213
214 By default `relative` is false, the frequency isn't rounded and will be
215 relative to the time when :program:`celery beat` was started.
216
217 .. _beat-crontab:
218
219 Crontab schedules
220 =================
221
222 If you want more control over when the task is executed, for
223 example, a particular time of day or day of the week, you can use
224 the :class:`~celery.schedules.crontab` schedule type:
225
226 .. code-block:: python
227
228 from celery.schedules import crontab
229
230 app.conf.beat_schedule = {
231 # Executes every Monday morning at 7:30 a.m.
232 'add-every-monday-morning': {
233 'task': 'tasks.add',
234 'schedule': crontab(hour=7, minute=30, day_of_week=1),
235 'args': (16, 16),
236 },
237 }
238
239 The syntax of these Crontab expressions are very flexible.
240
241 Some examples:
242
243 +-----------------------------------------+--------------------------------------------+
244 | **Example** | **Meaning** |
245 +-----------------------------------------+--------------------------------------------+
246 | ``crontab()`` | Execute every minute. |
247 +-----------------------------------------+--------------------------------------------+
248 | ``crontab(minute=0, hour=0)`` | Execute daily at midnight. |
249 +-----------------------------------------+--------------------------------------------+
250 | ``crontab(minute=0, hour='*/3')`` | Execute every three hours: |
251 | | midnight, 3am, 6am, 9am, |
252 | | noon, 3pm, 6pm, 9pm. |
253 +-----------------------------------------+--------------------------------------------+
254 | ``crontab(minute=0,`` | Same as previous. |
255 | ``hour='0,3,6,9,12,15,18,21')`` | |
256 +-----------------------------------------+--------------------------------------------+
257 | ``crontab(minute='*/15')`` | Execute every 15 minutes. |
258 +-----------------------------------------+--------------------------------------------+
259 | ``crontab(day_of_week='sunday')`` | Execute every minute (!) at Sundays. |
260 +-----------------------------------------+--------------------------------------------+
261 | ``crontab(minute='*',`` | Same as previous. |
262 | ``hour='*',`` | |
263 | ``day_of_week='sun')`` | |
264 +-----------------------------------------+--------------------------------------------+
265 | ``crontab(minute='*/10',`` | Execute every ten minutes, but only |
266 | ``hour='3,17,22',`` | between 3-4 am, 5-6 pm, and 10-11 pm on |
267 | ``day_of_week='thu,fri')`` | Thursdays or Fridays. |
268 +-----------------------------------------+--------------------------------------------+
269 | ``crontab(minute=0, hour='*/2,*/3')`` | Execute every even hour, and every hour |
270 | | divisible by three. This means: |
271 | | at every hour *except*: 1am, |
272 | | 5am, 7am, 11am, 1pm, 5pm, 7pm, |
273 | | 11pm |
274 +-----------------------------------------+--------------------------------------------+
275 | ``crontab(minute=0, hour='*/5')`` | Execute hour divisible by 5. This means |
276 | | that it is triggered at 3pm, not 5pm |
277 | | (since 3pm equals the 24-hour clock |
278 | | value of "15", which is divisible by 5). |
279 +-----------------------------------------+--------------------------------------------+
280 | ``crontab(minute=0, hour='*/3,8-17')`` | Execute every hour divisible by 3, and |
281 | | every hour during office hours (8am-5pm). |
282 +-----------------------------------------+--------------------------------------------+
283 | ``crontab(0, 0, day_of_month='2')`` | Execute on the second day of every month. |
284 | | |
285 +-----------------------------------------+--------------------------------------------+
286 | ``crontab(0, 0,`` | Execute on every even numbered day. |
287 | ``day_of_month='2-30/2')`` | |
288 +-----------------------------------------+--------------------------------------------+
289 | ``crontab(0, 0,`` | Execute on the first and third weeks of |
290 | ``day_of_month='1-7,15-21')`` | the month. |
291 +-----------------------------------------+--------------------------------------------+
292 | ``crontab(0, 0, day_of_month='11',`` | Execute on the eleventh of May every year. |
293 | ``month_of_year='5')`` | |
294 +-----------------------------------------+--------------------------------------------+
295 | ``crontab(0, 0,`` | Execute every day on the first month |
296 | ``month_of_year='*/3')`` | of every quarter. |
297 +-----------------------------------------+--------------------------------------------+
298
299 See :class:`celery.schedules.crontab` for more documentation.
300
301 .. _beat-solar:
302
303 Solar schedules
304 =================
305
306 If you have a task that should be executed according to sunrise,
307 sunset, dawn or dusk, you can use the
308 :class:`~celery.schedules.solar` schedule type:
309
310 .. code-block:: python
311
312 from celery.schedules import solar
313
314 app.conf.beat_schedule = {
315 # Executes at sunset in Melbourne
316 'add-at-melbourne-sunset': {
317 'task': 'tasks.add',
318 'schedule': solar('sunset', -37.81753, 144.96715),
319 'args': (16, 16),
320 },
321 }
322
323 The arguments are simply: ``solar(event, latitude, longitude)``
324
325 Be sure to use the correct sign for latitude and longitude:
326
327 +---------------+-------------------+----------------------+
328 | **Sign** | **Argument** | **Meaning** |
329 +---------------+-------------------+----------------------+
330 | ``+`` | ``latitude`` | North |
331 +---------------+-------------------+----------------------+
332 | ``-`` | ``latitude`` | South |
333 +---------------+-------------------+----------------------+
334 | ``+`` | ``longitude`` | East |
335 +---------------+-------------------+----------------------+
336 | ``-`` | ``longitude`` | West |
337 +---------------+-------------------+----------------------+
338
339 Possible event types are:
340
341 +-----------------------------------------+--------------------------------------------+
342 | **Event** | **Meaning** |
343 +-----------------------------------------+--------------------------------------------+
344 | ``dawn_astronomical`` | Execute at the moment after which the sky |
345 | | is no longer completely dark. This is when |
346 | | the sun is 18 degrees below the horizon. |
347 +-----------------------------------------+--------------------------------------------+
348 | ``dawn_nautical`` | Execute when there's enough sunlight for |
349 | | the horizon and some objects to be |
350 | | distinguishable; formally, when the sun is |
351 | | 12 degrees below the horizon. |
352 +-----------------------------------------+--------------------------------------------+
353 | ``dawn_civil`` | Execute when there's enough light for |
354 | | objects to be distinguishable so that |
355 | | outdoor activities can commence; |
356 | | formally, when the Sun is 6 degrees below |
357 | | the horizon. |
358 +-----------------------------------------+--------------------------------------------+
359 | ``sunrise`` | Execute when the upper edge of the sun |
360 | | appears over the eastern horizon in the |
361 | | morning. |
362 +-----------------------------------------+--------------------------------------------+
363 | ``solar_noon`` | Execute when the sun is highest above the |
364 | | horizon on that day. |
365 +-----------------------------------------+--------------------------------------------+
366 | ``sunset`` | Execute when the trailing edge of the sun |
367 | | disappears over the western horizon in the |
368 | | evening. |
369 +-----------------------------------------+--------------------------------------------+
370 | ``dusk_civil`` | Execute at the end of civil twilight, when |
371 | | objects are still distinguishable and some |
372 | | stars and planets are visible. Formally, |
373 | | when the sun is 6 degrees below the |
374 | | horizon. |
375 +-----------------------------------------+--------------------------------------------+
376 | ``dusk_nautical`` | Execute when the sun is 12 degrees below |
377 | | the horizon. Objects are no longer |
378 | | distinguishable, and the horizon is no |
379 | | longer visible to the naked eye. |
380 +-----------------------------------------+--------------------------------------------+
381 | ``dusk_astronomical`` | Execute at the moment after which the sky |
382 | | becomes completely dark; formally, when |
383 | | the sun is 18 degrees below the horizon. |
384 +-----------------------------------------+--------------------------------------------+
385
386 All solar events are calculated using UTC, and are therefore
387 unaffected by your timezone setting.
388
389 In polar regions, the sun may not rise or set every day. The scheduler
390 is able to handle these cases (i.e., a ``sunrise`` event won't run on a day
391 when the sun doesn't rise). The one exception is ``solar_noon``, which is
392 formally defined as the moment the sun transits the celestial meridian,
393 and will occur every day even if the sun is below the horizon.
394
395 Twilight is defined as the period between dawn and sunrise; and between
396 sunset and dusk. You can schedule an event according to "twilight"
397 depending on your definition of twilight (civil, nautical, or astronomical),
398 and whether you want the event to take place at the beginning or end
399 of twilight, using the appropriate event from the list above.
400
401 See :class:`celery.schedules.solar` for more documentation.
402
403 .. _beat-starting:
404
405 Starting the Scheduler
406 ======================
407
408 To start the :program:`celery beat` service:
409
410 .. code-block:: console
411
412 $ celery -A proj beat
413
414 You can also embed `beat` inside the worker by enabling the
415 workers :option:`-B <celery worker -B>` option, this is convenient if you'll
416 never run more than one worker node, but it's not commonly used and for that
417 reason isn't recommended for production use:
418
419 .. code-block:: console
420
421 $ celery -A proj worker -B
422
423 Beat needs to store the last run times of the tasks in a local database
424 file (named `celerybeat-schedule` by default), so it needs access to
425 write in the current directory, or alternatively you can specify a custom
426 location for this file:
427
428 .. code-block:: console
429
430 $ celery -A proj beat -s /home/celery/var/run/celerybeat-schedule
431
432
433 .. note::
434
435 To daemonize beat see :ref:`daemonizing`.
436
437 .. _beat-custom-schedulers:
438
439 Using custom scheduler classes
440 ------------------------------
441
442 Custom scheduler classes can be specified on the command-line (the
443 :option:`--scheduler <celery beat --scheduler>` argument).
444
445 The default scheduler is the :class:`celery.beat.PersistentScheduler`,
446 that simply keeps track of the last run times in a local :mod:`shelve`
447 database file.
448
449 There's also the :pypi:`django-celery-beat` extension that stores the schedule
450 in the Django database, and presents a convenient admin interface to manage
451 periodic tasks at runtime.
452
453 To install and use this extension:
454
455 #. Use :command:`pip` to install the package:
456
457 .. code-block:: console
458
459 $ pip install django-celery-beat
460
461 #. Add the ``django_celery_beat`` module to ``INSTALLED_APPS`` in your
462 Django project' :file:`settings.py`::
463
464 INSTALLED_APPS = (
465 ...,
466 'django_celery_beat',
467 )
468
469 Note that there is no dash in the module name, only underscores.
470
471 #. Apply Django database migrations so that the necessary tables are created:
472
473 .. code-block:: console
474
475 $ python manage.py migrate
476
477 #. Start the :program:`celery beat` service using the ``django_celery_beat.schedulers:DatabaseScheduler`` scheduler:
478
479 .. code-block:: console
480
481 $ celery -A proj beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler
482
483 Note: You may also add this as the :setting:`beat_scheduler` setting directly.
484
485 #. Visit the Django-Admin interface to set up some periodic tasks.