Debian Codegraph @

docs/userguide/tasks.rst

raw
1 .. _guide-tasks:
2
3 =====================================================================
4 Tasks
5 =====================================================================
6
7 Tasks are the building blocks of Celery applications.
8
9 A task is a class that can be created out of any callable. It performs
10 dual roles in that it defines both what happens when a task is
11 called (sends a message), and what happens when a worker receives that message.
12
13 Every task class has a unique name, and this name is referenced in messages
14 so the worker can find the right function to execute.
15
16 A task message is not removed from the queue
17 until that message has been :term:`acknowledged` by a worker. A worker can reserve
18 many messages in advance and even if the worker is killed -- by power failure
19 or some other reason -- the message will be redelivered to another worker.
20
21 Ideally task functions should be :term:`idempotent`: meaning
22 the function won't cause unintended effects even if called
23 multiple times with the same arguments.
24 Since the worker cannot detect if your tasks are idempotent, the default
25 behavior is to acknowledge the message in advance, just before it's executed,
26 so that a task invocation that already started is never executed again.
27
28 If your task is idempotent you can set the :attr:`~Task.acks_late` option
29 to have the worker acknowledge the message *after* the task returns
30 instead. See also the FAQ entry :ref:`faq-acks_late-vs-retry`.
31
32 Note that the worker will acknowledge the message if the child process executing
33 the task is terminated (either by the task calling :func:`sys.exit`, or by signal)
34 even when :attr:`~Task.acks_late` is enabled. This behavior is intentional
35 as...
36
37 #. We don't want to rerun tasks that forces the kernel to send
38 a :sig:`SIGSEGV` (segmentation fault) or similar signals to the process.
39 #. We assume that a system administrator deliberately killing the task
40 does not want it to automatically restart.
41 #. A task that allocates too much memory is in danger of triggering the kernel
42 OOM killer, the same may happen again.
43 #. A task that always fails when redelivered may cause a high-frequency
44 message loop taking down the system.
45
46 If you really want a task to be redelivered in these scenarios you should
47 consider enabling the :setting:`task_reject_on_worker_lost` setting.
48
49 .. warning::
50
51 A task that blocks indefinitely may eventually stop the worker instance
52 from doing any other work.
53
54 If your task does I/O then make sure you add timeouts to these operations,
55 like adding a timeout to a web request using the :pypi:`requests` library:
56
57 .. code-block:: python
58
59 connect_timeout, read_timeout = 5.0, 30.0
60 response = requests.get(URL, timeout=(connect_timeout, read_timeout))
61
62 :ref:`Time limits <worker-time-limits>` are convenient for making sure all
63 tasks return in a timely manner, but a time limit event will actually kill
64 the process by force so only use them to detect cases where you haven't
65 used manual timeouts yet.
66
67 In previous versions, the default prefork pool scheduler was not friendly
68 to long-running tasks, so if you had tasks that ran for minutes/hours, it
69 was advised to enable the :option:`-Ofair <celery worker -O>` command-line
70 argument to the :program:`celery worker`. However, as of version 4.0,
71 -Ofair is now the default scheduling strategy. See :ref:`optimizing-prefetch-limit`
72 for more information, and for the best performance route long-running and
73 short-running tasks to dedicated workers (:ref:`routing-automatic`).
74
75 If your worker hangs then please investigate what tasks are running
76 before submitting an issue, as most likely the hanging is caused
77 by one or more tasks hanging on a network operation.
78
79 --
80
81 In this chapter you'll learn all about defining tasks,
82 and this is the **table of contents**:
83
84 .. contents::
85 :local:
86 :depth: 1
87
88
89 .. _task-basics:
90
91 Basics
92 ======
93
94 You can easily create a task from any callable by using
95 the :meth:`@task` decorator:
96
97 .. code-block:: python
98
99 from .models import User
100
101 @app.task
102 def create_user(username, password):
103 User.objects.create(username=username, password=password)
104
105
106 There are also many :ref:`options <task-options>` that can be set for the task,
107 these can be specified as arguments to the decorator:
108
109 .. code-block:: python
110
111 @app.task(serializer='json')
112 def create_user(username, password):
113 User.objects.create(username=username, password=password)
114
115
116 How do I import the task decorator?
117 -----------------------------------
118
119 The task decorator is available on your :class:`@Celery` application instance,
120 if you don't know what this is then please read :ref:`first-steps`.
121
122 If you're using Django (see :ref:`django-first-steps`), or you're the author
123 of a library then you probably want to use the :func:`@shared_task` decorator:
124
125 .. code-block:: python
126
127 from celery import shared_task
128
129 @shared_task
130 def add(x, y):
131 return x + y
132
133 Multiple decorators
134 -------------------
135
136 When using multiple decorators in combination with the task
137 decorator you must make sure that the `task`
138 decorator is applied last (oddly, in Python this means it must
139 be first in the list):
140
141 .. code-block:: python
142
143 @app.task
144 @decorator2
145 @decorator1
146 def add(x, y):
147 return x + y
148
149 Bound tasks
150 -----------
151
152 A task being bound means the first argument to the task will always
153 be the task instance (``self``), just like Python bound methods:
154
155 .. code-block:: python
156
157 logger = get_task_logger(__name__)
158
159 @app.task(bind=True)
160 def add(self, x, y):
161 logger.info(self.request.id)
162
163 Bound tasks are needed for retries (using :meth:`Task.retry() <@Task.retry>`),
164 for accessing information about the current task request, and for any
165 additional functionality you add to custom task base classes.
166
167 Task inheritance
168 ----------------
169
170 The ``base`` argument to the task decorator specifies the base class of the task:
171
172 .. code-block:: python
173
174 import celery
175
176 class MyTask(celery.Task):
177
178 def on_failure(self, exc, task_id, args, kwargs, einfo):
179 print('{0!r} failed: {1!r}'.format(task_id, exc))
180
181 @app.task(base=MyTask)
182 def add(x, y):
183 raise KeyError()
184
185 .. _task-names:
186
187 Names
188 =====
189
190 Every task must have a unique name.
191
192 If no explicit name is provided the task decorator will generate one for you,
193 and this name will be based on 1) the module the task is defined in, and 2)
194 the name of the task function.
195
196 Example setting explicit name:
197
198 .. code-block:: pycon
199
200 >>> @app.task(name='sum-of-two-numbers')
201 >>> def add(x, y):
202 ... return x + y
203
204 >>> add.name
205 'sum-of-two-numbers'
206
207 A best practice is to use the module name as a name-space,
208 this way names won't collide if there's already a task with that name
209 defined in another module.
210
211 .. code-block:: pycon
212
213 >>> @app.task(name='tasks.add')
214 >>> def add(x, y):
215 ... return x + y
216
217 You can tell the name of the task by investigating its ``.name`` attribute:
218
219 .. code-block:: pycon
220
221 >>> add.name
222 'tasks.add'
223
224 The name we specified here (``tasks.add``) is exactly the name that would've
225 been automatically generated for us if the task was defined in a module
226 named :file:`tasks.py`:
227
228 :file:`tasks.py`:
229
230 .. code-block:: python
231
232 @app.task
233 def add(x, y):
234 return x + y
235
236 .. code-block:: pycon
237
238 >>> from tasks import add
239 >>> add.name
240 'tasks.add'
241
242 .. note::
243
244 You can use the `inspect` command in a worker to view the names of
245 all registered tasks. See the `inspect registered` command in the
246 :ref:`monitoring-control` section of the User Guide.
247
248 .. _task-name-generator-info:
249
250 Changing the automatic naming behavior
251 --------------------------------------
252
253 .. versionadded:: 4.0
254
255 There are some cases when the default automatic naming isn't suitable.
256 Consider having many tasks within many different modules::
257
258 project/
259 /__init__.py
260 /celery.py
261 /moduleA/
262 /__init__.py
263 /tasks.py
264 /moduleB/
265 /__init__.py
266 /tasks.py
267
268 Using the default automatic naming, each task will have a generated name
269 like `moduleA.tasks.taskA`, `moduleA.tasks.taskB`, `moduleB.tasks.test`,
270 and so on. You may want to get rid of having `tasks` in all task names.
271 As pointed above, you can explicitly give names for all tasks, or you
272 can change the automatic naming behavior by overriding
273 :meth:`@gen_task_name`. Continuing with the example, `celery.py`
274 may contain:
275
276 .. code-block:: python
277
278 from celery import Celery
279
280 class MyCelery(Celery):
281
282 def gen_task_name(self, name, module):
283 if module.endswith('.tasks'):
284 module = module[:-6]
285 return super().gen_task_name(name, module)
286
287 app = MyCelery('main')
288
289 So each task will have a name like `moduleA.taskA`, `moduleA.taskB` and
290 `moduleB.test`.
291
292 .. warning::
293
294 Make sure that your :meth:`@gen_task_name` is a pure function: meaning
295 that for the same input it must always return the same output.
296
297 .. _task-request-info:
298
299 Task Request
300 ============
301
302 :attr:`Task.request <@Task.request>` contains information and state
303 related to the currently executing task.
304
305 The request defines the following attributes:
306
307 :id: The unique id of the executing task.
308
309 :group: The unique id of the task's :ref:`group <canvas-group>`, if this task is a member.
310
311 :chord: The unique id of the chord this task belongs to (if the task
312 is part of the header).
313
314 :correlation_id: Custom ID used for things like de-duplication.
315
316 :args: Positional arguments.
317
318 :kwargs: Keyword arguments.
319
320 :origin: Name of host that sent this task.
321
322 :retries: How many times the current task has been retried.
323 An integer starting at `0`.
324
325 :is_eager: Set to :const:`True` if the task is executed locally in
326 the client, not by a worker.
327
328 :eta: The original ETA of the task (if any).
329 This is in UTC time (depending on the :setting:`enable_utc`
330 setting).
331
332 :expires: The original expiry time of the task (if any).
333 This is in UTC time (depending on the :setting:`enable_utc`
334 setting).
335
336 :hostname: Node name of the worker instance executing the task.
337
338 :delivery_info: Additional message delivery information. This is a mapping
339 containing the exchange and routing key used to deliver this
340 task. Used by for example :meth:`Task.retry() <@Task.retry>`
341 to resend the task to the same destination queue.
342 Availability of keys in this dict depends on the
343 message broker used.
344
345 :reply-to: Name of queue to send replies back to (used with RPC result
346 backend for example).
347
348 :called_directly: This flag is set to true if the task wasn't
349 executed by the worker.
350
351 :timelimit: A tuple of the current ``(soft, hard)`` time limits active for
352 this task (if any).
353
354 :callbacks: A list of signatures to be called if this task returns successfully.
355
356 :errbacks: A list of signatures to be called if this task fails.
357
358 :utc: Set to true the caller has UTC enabled (:setting:`enable_utc`).
359
360
361 .. versionadded:: 3.1
362
363 :headers: Mapping of message headers sent with this task message
364 (may be :const:`None`).
365
366 :reply_to: Where to send reply to (queue name).
367
368 :correlation_id: Usually the same as the task id, often used in amqp
369 to keep track of what a reply is for.
370
371 .. versionadded:: 4.0
372
373 :root_id: The unique id of the first task in the workflow this task
374 is part of (if any).
375
376 :parent_id: The unique id of the task that called this task (if any).
377
378 :chain: Reversed list of tasks that form a chain (if any).
379 The last item in this list will be the next task to succeed the
380 current task. If using version one of the task protocol the chain
381 tasks will be in ``request.callbacks`` instead.
382
383 .. versionadded:: 5.2
384
385 :properties: Mapping of message properties received with this task message
386 (may be :const:`None` or :const:`{}`)
387
388 :replaced_task_nesting: How many times the task was replaced, if at all.
389 (may be :const:`0`)
390
391 Example
392 -------
393
394 An example task accessing information in the context is:
395
396 .. code-block:: python
397
398 @app.task(bind=True)
399 def dump_context(self, x, y):
400 print('Executing task id {0.id}, args: {0.args!r} kwargs: {0.kwargs!r}'.format(
401 self.request))
402
403
404 The ``bind`` argument means that the function will be a "bound method" so
405 that you can access attributes and methods on the task type instance.
406
407 .. _task-logging:
408
409 Logging
410 =======
411
412 The worker will automatically set up logging for you, or you can
413 configure logging manually.
414
415 A special logger is available named "celery.task", you can inherit
416 from this logger to automatically get the task name and unique id as part
417 of the logs.
418
419 The best practice is to create a common logger
420 for all of your tasks at the top of your module:
421
422 .. code-block:: python
423
424 from celery.utils.log import get_task_logger
425
426 logger = get_task_logger(__name__)
427
428 @app.task
429 def add(x, y):
430 logger.info('Adding {0} + {1}'.format(x, y))
431 return x + y
432
433 Celery uses the standard Python logger library,
434 and the documentation can be found :mod:`here <logging>`.
435
436 You can also use :func:`print`, as anything written to standard
437 out/-err will be redirected to the logging system (you can disable this,
438 see :setting:`worker_redirect_stdouts`).
439
440 .. note::
441
442 The worker won't update the redirection if you create a logger instance
443 somewhere in your task or task module.
444
445 If you want to redirect ``sys.stdout`` and ``sys.stderr`` to a custom
446 logger you have to enable this manually, for example:
447
448 .. code-block:: python
449
450 import sys
451
452 logger = get_task_logger(__name__)
453
454 @app.task(bind=True)
455 def add(self, x, y):
456 old_outs = sys.stdout, sys.stderr
457 rlevel = self.app.conf.worker_redirect_stdouts_level
458 try:
459 self.app.log.redirect_stdouts_to_logger(logger, rlevel)
460 print('Adding {0} + {1}'.format(x, y))
461 return x + y
462 finally:
463 sys.stdout, sys.stderr = old_outs
464
465
466 .. note::
467
468 If a specific Celery logger you need is not emitting logs, you should
469 check that the logger is propagating properly. In this example
470 "celery.app.trace" is enabled so that "succeeded in" logs are emitted:
471
472 .. code-block:: python
473
474
475 import celery
476 import logging
477
478 @celery.signals.after_setup_logger.connect
479 def on_after_setup_logger(**kwargs):
480 logger = logging.getLogger('celery')
481 logger.propagate = True
482 logger = logging.getLogger('celery.app.trace')
483 logger.propagate = True
484
485
486 .. note::
487
488 If you want to completely disable Celery logging configuration,
489 use the :signal:`setup_logging` signal:
490
491 .. code-block:: python
492
493 import celery
494
495 @celery.signals.setup_logging.connect
496 def on_setup_logging(**kwargs):
497 pass
498
499
500 .. _task-argument-checking:
501
502 Argument checking
503 -----------------
504
505 .. versionadded:: 4.0
506
507 Celery will verify the arguments passed when you call the task, just
508 like Python does when calling a normal function:
509
510 .. code-block:: pycon
511
512 >>> @app.task
513 ... def add(x, y):
514 ... return x + y
515
516 # Calling the task with two arguments works:
517 >>> add.delay(8, 8)
518 <AsyncResult: f59d71ca-1549-43e0-be41-4e8821a83c0c>
519
520 # Calling the task with only one argument fails:
521 >>> add.delay(8)
522 Traceback (most recent call last):
523 File "<stdin>", line 1, in <module>
524 File "celery/app/task.py", line 376, in delay
525 return self.apply_async(args, kwargs)
526 File "celery/app/task.py", line 485, in apply_async
527 check_arguments(*(args or ()), **(kwargs or {}))
528 TypeError: add() takes exactly 2 arguments (1 given)
529
530 You can disable the argument checking for any task by setting its
531 :attr:`[email protected]` attribute to :const:`False`:
532
533 .. code-block:: pycon
534
535 >>> @app.task(typing=False)
536 ... def add(x, y):
537 ... return x + y
538
539 # Works locally, but the worker receiving the task will raise an error.
540 >>> add.delay(8)
541 <AsyncResult: f59d71ca-1549-43e0-be41-4e8821a83c0c>
542
543 .. _task-hiding-sensitive-information:
544
545 Hiding sensitive information in arguments
546 -----------------------------------------
547
548 .. versionadded:: 4.0
549
550 When using :setting:`task_protocol` 2 or higher (default since 4.0), you can
551 override how positional arguments and keyword arguments are represented in logs
552 and monitoring events using the ``argsrepr`` and ``kwargsrepr`` calling
553 arguments:
554
555 .. code-block:: pycon
556
557 >>> add.apply_async((2, 3), argsrepr='(<secret-x>, <secret-y>)')
558
559 >>> charge.s(account, card='1234 5678 1234 5678').set(
560 ... kwargsrepr=repr({'card': '**** **** **** 5678'})
561 ... ).delay()
562
563
564 .. warning::
565
566 Sensitive information will still be accessible to anyone able
567 to read your task message from the broker, or otherwise able intercept it.
568
569 For this reason you should probably encrypt your message if it contains
570 sensitive information, or in this example with a credit card number
571 the actual number could be stored encrypted in a secure store that you retrieve
572 and decrypt in the task itself.
573
574 .. _task-retry:
575
576 Retrying
577 ========
578
579 :meth:`Task.retry() <@Task.retry>` can be used to re-execute the task,
580 for example in the event of recoverable errors.
581
582 When you call ``retry`` it'll send a new message, using the same
583 task-id, and it'll take care to make sure the message is delivered
584 to the same queue as the originating task.
585
586 When a task is retried this is also recorded as a task state,
587 so that you can track the progress of the task using the result
588 instance (see :ref:`task-states`).
589
590 Here's an example using ``retry``:
591
592 .. code-block:: python
593
594 @app.task(bind=True)
595 def send_twitter_status(self, oauth, tweet):
596 try:
597 twitter = Twitter(oauth)
598 twitter.update_status(tweet)
599 except (Twitter.FailWhaleError, Twitter.LoginError) as exc:
600 raise self.retry(exc=exc)
601
602 .. note::
603
604 The :meth:`Task.retry() <@Task.retry>` call will raise an exception so any
605 code after the retry won't be reached. This is the :exc:`~@Retry`
606 exception, it isn't handled as an error but rather as a semi-predicate
607 to signify to the worker that the task is to be retried,
608 so that it can store the correct state when a result backend is enabled.
609
610 This is normal operation and always happens unless the
611 ``throw`` argument to retry is set to :const:`False`.
612
613 The bind argument to the task decorator will give access to ``self`` (the
614 task type instance).
615
616 The ``exc`` argument is used to pass exception information that's
617 used in logs, and when storing task results.
618 Both the exception and the traceback will
619 be available in the task state (if a result backend is enabled).
620
621 If the task has a ``max_retries`` value the current exception
622 will be re-raised if the max number of retries has been exceeded,
623 but this won't happen if:
624
625 - An ``exc`` argument wasn't given.
626
627 In this case the :exc:`~@MaxRetriesExceededError`
628 exception will be raised.
629
630 - There's no current exception
631
632 If there's no original exception to re-raise the ``exc``
633 argument will be used instead, so:
634
635 .. code-block:: python
636
637 self.retry(exc=Twitter.LoginError())
638
639 will raise the ``exc`` argument given.
640
641 .. _task-retry-custom-delay:
642
643 Using a custom retry delay
644 --------------------------
645
646 When a task is to be retried, it can wait for a given amount of time
647 before doing so, and the default delay is defined by the
648 :attr:`[email protected]_retry_delay`
649 attribute. By default this is set to 3 minutes. Note that the
650 unit for setting the delay is in seconds (int or float).
651
652 You can also provide the `countdown` argument to :meth:`[email protected]` to
653 override this default.
654
655 .. code-block:: python
656
657 @app.task(bind=True, default_retry_delay=30 * 60) # retry in 30 minutes.
658 def add(self, x, y):
659 try:
660 something_raising()
661 except Exception as exc:
662 # overrides the default delay to retry after 1 minute
663 raise self.retry(exc=exc, countdown=60)
664
665 .. _task-autoretry:
666
667 Automatic retry for known exceptions
668 ------------------------------------
669
670 .. versionadded:: 4.0
671
672 Sometimes you just want to retry a task whenever a particular exception
673 is raised.
674
675 Fortunately, you can tell Celery to automatically retry a task using
676 `autoretry_for` argument in the :meth:`@task` decorator:
677
678 .. code-block:: python
679
680 from twitter.exceptions import FailWhaleError
681
682 @app.task(autoretry_for=(FailWhaleError,))
683 def refresh_timeline(user):
684 return twitter.refresh_timeline(user)
685
686 If you want to specify custom arguments for an internal :meth:`[email protected]`
687 call, pass `retry_kwargs` argument to :meth:`@task` decorator:
688
689 .. code-block:: python
690
691 @app.task(autoretry_for=(FailWhaleError,),
692 retry_kwargs={'max_retries': 5})
693 def refresh_timeline(user):
694 return twitter.refresh_timeline(user)
695
696 This is provided as an alternative to manually handling the exceptions,
697 and the example above will do the same as wrapping the task body
698 in a :keyword:`try` ... :keyword:`except` statement:
699
700 .. code-block:: python
701
702 @app.task
703 def refresh_timeline(user):
704 try:
705 twitter.refresh_timeline(user)
706 except FailWhaleError as exc:
707 raise refresh_timeline.retry(exc=exc, max_retries=5)
708
709 If you want to automatically retry on any error, simply use:
710
711 .. code-block:: python
712
713 @app.task(autoretry_for=(Exception,))
714 def x():
715 ...
716
717 .. versionadded:: 4.2
718
719 If your tasks depend on another service, like making a request to an API,
720 then it's a good idea to use `exponential backoff`_ to avoid overwhelming the
721 service with your requests. Fortunately, Celery's automatic retry support
722 makes it easy. Just specify the :attr:`~Task.retry_backoff` argument, like this:
723
724 .. code-block:: python
725
726 from requests.exceptions import RequestException
727
728 @app.task(autoretry_for=(RequestException,), retry_backoff=True)
729 def x():
730 ...
731
732 By default, this exponential backoff will also introduce random jitter_ to
733 avoid having all the tasks run at the same moment. It will also cap the
734 maximum backoff delay to 10 minutes. All these settings can be customized
735 via options documented below.
736
737 .. versionadded:: 4.4
738
739 You can also set `autoretry_for`, `max_retries`, `retry_backoff`, `retry_backoff_max` and `retry_jitter` options in class-based tasks:
740
741 .. code-block:: python
742
743 class BaseTaskWithRetry(Task):
744 autoretry_for = (TypeError,)
745 max_retries = 5
746 retry_backoff = True
747 retry_backoff_max = 700
748 retry_jitter = False
749
750 .. attribute:: Task.autoretry_for
751
752 A list/tuple of exception classes. If any of these exceptions are raised
753 during the execution of the task, the task will automatically be retried.
754 By default, no exceptions will be autoretried.
755
756 .. attribute:: Task.max_retries
757
758 A number. Maximum number of retries before giving up. A value of ``None``
759 means task will retry forever. By default, this option is set to ``3``.
760
761 .. attribute:: Task.retry_backoff
762
763 A boolean, or a number. If this option is set to ``True``, autoretries
764 will be delayed following the rules of `exponential backoff`_. The first
765 retry will have a delay of 1 second, the second retry will have a delay
766 of 2 seconds, the third will delay 4 seconds, the fourth will delay 8
767 seconds, and so on. (However, this delay value is modified by
768 :attr:`~Task.retry_jitter`, if it is enabled.)
769 If this option is set to a number, it is used as a
770 delay factor. For example, if this option is set to ``3``, the first retry
771 will delay 3 seconds, the second will delay 6 seconds, the third will
772 delay 12 seconds, the fourth will delay 24 seconds, and so on. By default,
773 this option is set to ``False``, and autoretries will not be delayed.
774
775 .. attribute:: Task.retry_backoff_max
776
777 A number. If ``retry_backoff`` is enabled, this option will set a maximum
778 delay in seconds between task autoretries. By default, this option is set to ``600``,
779 which is 10 minutes.
780
781 .. attribute:: Task.retry_jitter
782
783 A boolean. `Jitter`_ is used to introduce randomness into
784 exponential backoff delays, to prevent all tasks in the queue from being
785 executed simultaneously. If this option is set to ``True``, the delay
786 value calculated by :attr:`~Task.retry_backoff` is treated as a maximum,
787 and the actual delay value will be a random number between zero and that
788 maximum. By default, this option is set to ``True``.
789
790 .. versionadded:: 5.3.0
791
792 .. attribute:: Task.dont_autoretry_for
793
794 A list/tuple of exception classes. These exceptions won't be autoretried.
795 This allows to exclude some exceptions that match `autoretry_for
796 <Task.autoretry_for>`:attr: but for which you don't want a retry.
797
798 .. _task-pydantic:
799
800 Argument validation with Pydantic
801 =================================
802
803 .. versionadded:: 5.5.0
804
805 You can use Pydantic_ to validate and convert arguments as well as serializing
806 results based on typehints by passing ``pydantic=True``.
807
808 .. NOTE::
809
810 Argument validation only covers arguments/return values on the task side. You still have
811 serialize arguments yourself when invoking a task with ``delay()`` or ``apply_async()``.
812
813 For example:
814
815 .. code-block:: python
816
817 from pydantic import BaseModel
818
819 class ArgModel(BaseModel):
820 value: int
821
822 class ReturnModel(BaseModel):
823 value: str
824
825 @app.task(pydantic=True)
826 def x(arg: ArgModel) -> ReturnModel:
827 # args/kwargs type hinted as Pydantic model will be converted
828 assert isinstance(arg, ArgModel)
829
830 # The returned model will be converted to a dict automatically
831 return ReturnModel(value=f"example: {arg.value}")
832
833 The task can then be called using a dict matching the model, and you'll receive
834 the returned model "dumped" (serialized using ``BaseModel.model_dump()``):
835
836 .. code-block:: python
837
838 >>> result = x.delay({'value': 1})
839 >>> result.get(timeout=1)
840 {'value': 'example: 1'}
841
842 Union types, arguments to generics
843 ----------------------------------
844
845 Union types (e.g. ``Union[SomeModel, OtherModel]``) or arguments to generics (e.g.
846 ``list[SomeModel]``) are **not** supported.
847
848 In case you want to support a list or similar types, it is recommended to use
849 ``pydantic.RootModel``.
850
851
852 Optional parameters/return values
853 ---------------------------------
854
855 Optional parameters or return values are also handled properly. For example, given this task:
856
857 .. code-block:: python
858
859 from typing import Optional
860
861 # models are the same as above
862
863 @app.task(pydantic=True)
864 def x(arg: Optional[ArgModel] = None) -> Optional[ReturnModel]:
865 if arg is None:
866 return None
867 return ReturnModel(value=f"example: {arg.value}")
868
869 You'll get the following behavior:
870
871 .. code-block:: python
872
873 >>> result = x.delay()
874 >>> result.get(timeout=1) is None
875 True
876 >>> result = x.delay({'value': 1})
877 >>> result.get(timeout=1)
878 {'value': 'example: 1'}
879
880 Return value handling
881 ---------------------
882
883 Return values will only be serialized if the returned model matches the annotation. If you pass a
884 model instance of a different type, it will *not* be serialized. ``mypy`` should already catch such
885 errors and you should fix your typehints then.
886
887
888 Pydantic parameters
889 -------------------
890
891 There are a few more options influencing Pydantic behavior:
892
893 .. attribute:: Task.pydantic_strict
894
895 By default, `strict mode <https://docs.pydantic.dev/dev/concepts/strict_mode/>`_
896 is disabled. You can pass ``True`` to enable strict model validation.
897
898 .. attribute:: Task.pydantic_context
899
900 Pass `additional validation context
901 <https://docs.pydantic.dev/dev/concepts/validators/#validation-context>`_ during
902 Pydantic model validation. The context already includes the application object as
903 ``celery_app`` and the task name as ``celery_task_name`` by default.
904
905 .. attribute:: Task.pydantic_dump_kwargs
906
907 When serializing a result, pass these additional arguments to ``dump_kwargs()``.
908 By default, only ``mode='json'`` is passed.
909
910
911 .. _task-options:
912
913 List of Options
914 ===============
915
916 The task decorator can take a number of options that change the way
917 the task behaves, for example you can set the rate limit for a task
918 using the :attr:`rate_limit` option.
919
920 Any keyword argument passed to the task decorator will actually be set
921 as an attribute of the resulting task class, and this is a list
922 of the built-in attributes.
923
924 General
925 -------
926
927 .. _task-general-options:
928
929 .. attribute:: Task.name
930
931 The name the task is registered as.
932
933 You can set this name manually, or a name will be
934 automatically generated using the module and class name.
935
936 See also :ref:`task-names`.
937
938 .. attribute:: Task.request
939
940 If the task is being executed this will contain information
941 about the current request. Thread local storage is used.
942
943 See :ref:`task-request-info`.
944
945 .. attribute:: Task.max_retries
946
947 Only applies if the task calls ``self.retry`` or if the task is decorated
948 with the :ref:`autoretry_for <task-autoretry>` argument.
949
950 The maximum number of attempted retries before giving up.
951 If the number of retries exceeds this value a :exc:`~@MaxRetriesExceededError`
952 exception will be raised.
953
954 .. note::
955
956 You have to call :meth:`[email protected]`
957 manually, as it won't automatically retry on exception..
958
959 The default is ``3``.
960 A value of :const:`None` will disable the retry limit and the
961 task will retry forever until it succeeds.
962
963 .. attribute:: Task.throws
964
965 Optional tuple of expected error classes that shouldn't be regarded
966 as an actual error.
967
968 Errors in this list will be reported as a failure to the result backend,
969 but the worker won't log the event as an error, and no traceback will
970 be included.
971
972 Example:
973
974 .. code-block:: python
975
976 @task(throws=(KeyError, HttpNotFound)):
977 def get_foo():
978 something()
979
980 Error types:
981
982 - Expected errors (in ``Task.throws``)
983
984 Logged with severity ``INFO``, traceback excluded.
985
986 - Unexpected errors
987
988 Logged with severity ``ERROR``, with traceback included.
989
990 .. attribute:: Task.default_retry_delay
991
992 Default time in seconds before a retry of the task
993 should be executed. Can be either :class:`int` or :class:`float`.
994 Default is a three minute delay.
995
996 .. attribute:: Task.rate_limit
997
998 Set the rate limit for this task type (limits the number of tasks
999 that can be run in a given time frame). Tasks will still complete when
1000 a rate limit is in effect, but it may take some time before it's allowed to
1001 start.
1002
1003 If this is :const:`None` no rate limit is in effect.
1004 If it is an integer or float, it is interpreted as "tasks per second".
1005
1006 The rate limits can be specified in seconds, minutes or hours
1007 by appending `"/s"`, `"/m"` or `"/h"` to the value. Tasks will be evenly
1008 distributed over the specified time frame.
1009
1010 Example: `"100/m"` (hundred tasks a minute). This will enforce a minimum
1011 delay of 600ms between starting two tasks on the same worker instance.
1012
1013 Default is the :setting:`task_default_rate_limit` setting:
1014 if not specified means rate limiting for tasks is disabled by default.
1015
1016 Note that this is a *per worker instance* rate limit, and not a global
1017 rate limit. To enforce a global rate limit (e.g., for an API with a
1018 maximum number of requests per second), you must restrict to a given
1019 queue.
1020
1021 .. attribute:: Task.time_limit
1022
1023 The hard time limit, in seconds, for this task.
1024 When not set the workers default is used.
1025
1026 .. attribute:: Task.soft_time_limit
1027
1028 The soft time limit for this task.
1029 When not set the workers default is used.
1030
1031 .. attribute:: Task.ignore_result
1032
1033 Don't store task state. Note that this means you can't use
1034 :class:`~celery.result.AsyncResult` to check if the task is ready,
1035 or get its return value.
1036
1037 Note: Certain features will not work if task results are disabled.
1038 For more details check the Canvas documentation.
1039
1040 .. attribute:: Task.store_errors_even_if_ignored
1041
1042 If :const:`True`, errors will be stored even if the task is configured
1043 to ignore results.
1044
1045 .. versionchanged:: 5.7
1046 Previously, if the ``ignore_result`` key was missing from the request
1047 message, ``store_errors`` would default to ``True``, ignoring the
1048 task's own ``ignore_result`` setting. The worker now correctly
1049 falls back to ``Task.ignore_result`` when no per-request override
1050 is present.
1051
1052 .. attribute:: Task.serializer
1053
1054 A string identifying the default serialization
1055 method to use. Defaults to the :setting:`task_serializer`
1056 setting. Can be `pickle`, `json`, `yaml`, or any custom
1057 serialization methods that have been registered with
1058 :mod:`kombu.serialization.registry`.
1059
1060 Please see :ref:`calling-serializers` for more information.
1061
1062 .. attribute:: Task.compression
1063
1064 A string identifying the default compression scheme to use.
1065
1066 Defaults to the :setting:`task_compression` setting.
1067 Can be `gzip`, or `bzip2`, or any custom compression schemes
1068 that have been registered with the :mod:`kombu.compression` registry.
1069
1070 Please see :ref:`calling-compression` for more information.
1071
1072 .. attribute:: Task.backend
1073
1074 The result store backend to use for this task. An instance of one of the
1075 backend classes in `celery.backends`. Defaults to `app.backend`,
1076 defined by the :setting:`result_backend` setting.
1077
1078 .. attribute:: Task.acks_late
1079
1080 If set to :const:`True` messages for this task will be acknowledged
1081 **after** the task has been executed, not *just before* (the default
1082 behavior).
1083
1084 Note: This means the task may be executed multiple times should the worker
1085 crash in the middle of execution. Make sure your tasks are
1086 :term:`idempotent`.
1087
1088 The global default can be overridden by the :setting:`task_acks_late`
1089 setting.
1090
1091 .. _task-track-started:
1092
1093 .. attribute:: Task.track_started
1094
1095 If :const:`True` the task will report its status as "started"
1096 when the task is executed by a worker.
1097 The default value is :const:`False` as the normal behavior is to not
1098 report that level of granularity. Tasks are either pending, finished,
1099 or waiting to be retried. Having a "started" status can be useful for
1100 when there are long running tasks and there's a need to report what
1101 task is currently running.
1102
1103 The host name and process id of the worker executing the task
1104 will be available in the state meta-data (e.g., `result.info['pid']`)
1105
1106 The global default can be overridden by the
1107 :setting:`task_track_started` setting.
1108
1109
1110 .. seealso::
1111
1112 The API reference for :class:`~@Task`.
1113
1114 .. _task-states:
1115
1116 States
1117 ======
1118
1119 Celery can keep track of the tasks current state. The state also contains the
1120 result of a successful task, or the exception and traceback information of a
1121 failed task.
1122
1123 There are several *result backends* to choose from, and they all have
1124 different strengths and weaknesses (see :ref:`task-result-backends`).
1125
1126 During its lifetime a task will transition through several possible states,
1127 and each state may have arbitrary meta-data attached to it. When a task
1128 moves into a new state the previous state is
1129 forgotten about, but some transitions can be deduced, (e.g., a task now
1130 in the :state:`FAILED` state, is implied to have been in the
1131 :state:`STARTED` state at some point).
1132
1133 There are also sets of states, like the set of
1134 :state:`FAILURE_STATES`, and the set of :state:`READY_STATES`.
1135
1136 The client uses the membership of these sets to decide whether
1137 the exception should be re-raised (:state:`PROPAGATE_STATES`), or whether
1138 the state can be cached (it can if the task is ready).
1139
1140 You can also define :ref:`custom-states`.
1141
1142 .. _task-result-backends:
1143
1144 Result Backends
1145 ---------------
1146
1147 If you want to keep track of tasks or need the return values, then Celery
1148 must store or send the states somewhere so that they can be retrieved later.
1149 There are several built-in result backends to choose from: SQLAlchemy/Django ORM,
1150 Memcached, RabbitMQ/QPid (``rpc``), and Redis -- or you can define your own.
1151
1152 No backend works well for every use case.
1153 You should read about the strengths and weaknesses of each backend, and choose
1154 the most appropriate for your needs.
1155
1156 .. warning::
1157
1158 Backends use resources to store and transmit results. To ensure
1159 that resources are released, you must eventually call
1160 :meth:`[email protected]` or :meth:`[email protected]` on
1161 EVERY :class:`~@AsyncResult` instance returned after calling
1162 a task.
1163
1164 .. seealso::
1165
1166 :ref:`conf-result-backend`
1167
1168 RPC Result Backend (RabbitMQ/QPid)
1169 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1170
1171 The RPC result backend (`rpc://`) is special as it doesn't actually *store*
1172 the states, but rather sends them as messages. This is an important difference as it
1173 means that a result *can only be retrieved once*, and *only by the client
1174 that initiated the task*. Two different processes can't wait for the same result.
1175
1176 Even with that limitation, it is an excellent choice if you need to receive
1177 state changes in real-time. Using messaging means the client doesn't have to
1178 poll for new states.
1179
1180 The messages are transient (non-persistent) by default, so the results will
1181 disappear if the broker restarts. You can configure the result backend to send
1182 persistent messages using the :setting:`result_persistent` setting.
1183
1184 Database Result Backend
1185 ~~~~~~~~~~~~~~~~~~~~~~~
1186
1187 Keeping state in the database can be convenient for many, especially for
1188 web applications with a database already in place, but it also comes with
1189 limitations.
1190
1191 * Polling the database for new states is expensive, and so you should
1192 increase the polling intervals of operations, such as `result.get()`.
1193
1194 * Some databases use a default transaction isolation level that
1195 isn't suitable for polling tables for changes.
1196
1197 In MySQL the default transaction isolation level is `REPEATABLE-READ`:
1198 meaning the transaction won't see changes made by other transactions until
1199 the current transaction is committed.
1200
1201 Changing that to the `READ-COMMITTED` isolation level is recommended.
1202
1203 .. _task-builtin-states:
1204
1205 Built-in States
1206 ---------------
1207
1208 .. state:: PENDING
1209
1210 PENDING
1211 ~~~~~~~
1212
1213 Task is waiting for execution or unknown.
1214 Any task id that's not known is implied to be in the pending state.
1215
1216 .. state:: STARTED
1217
1218 STARTED
1219 ~~~~~~~
1220
1221 Task has been started.
1222 Not reported by default, to enable please see :attr:`@Task.track_started`.
1223
1224 :meta-data: `pid` and `hostname` of the worker process executing
1225 the task.
1226
1227 .. state:: SUCCESS
1228
1229 SUCCESS
1230 ~~~~~~~
1231
1232 Task has been successfully executed.
1233
1234 :meta-data: `result` contains the return value of the task.
1235 :propagates: Yes
1236 :ready: Yes
1237
1238 .. state:: FAILURE
1239
1240 FAILURE
1241 ~~~~~~~
1242
1243 Task execution resulted in failure.
1244
1245 :meta-data: `result` contains the exception occurred, and `traceback`
1246 contains the backtrace of the stack at the point when the
1247 exception was raised.
1248 :propagates: Yes
1249
1250 .. state:: RETRY
1251
1252 RETRY
1253 ~~~~~
1254
1255 Task is being retried.
1256
1257 :meta-data: `result` contains the exception that caused the retry,
1258 and `traceback` contains the backtrace of the stack at the point
1259 when the exceptions was raised.
1260 :propagates: No
1261
1262 .. state:: REVOKED
1263
1264 REVOKED
1265 ~~~~~~~
1266
1267 Task has been revoked.
1268
1269 :propagates: Yes
1270
1271 .. _custom-states:
1272
1273 Custom states
1274 -------------
1275
1276 You can easily define your own states, all you need is a unique name.
1277 The name of the state is usually an uppercase string. As an example
1278 you could have a look at the :mod:`abortable tasks <~celery.contrib.abortable>`
1279 which defines a custom :state:`ABORTED` state.
1280
1281 Use :meth:`[email protected]_state` to update a task's state:.
1282
1283 .. code-block:: python
1284
1285 @app.task(bind=True)
1286 def upload_files(self, filenames):
1287 for i, file in enumerate(filenames):
1288 if not self.request.called_directly:
1289 self.update_state(state='PROGRESS',
1290 meta={'current': i, 'total': len(filenames)})
1291
1292
1293 Here I created the state `"PROGRESS"`, telling any application
1294 aware of this state that the task is currently in progress, and also where
1295 it is in the process by having `current` and `total` counts as part of the
1296 state meta-data. This can then be used to create progress bars for example.
1297
1298 .. _pickling_exceptions:
1299
1300 Creating pickleable exceptions
1301 ------------------------------
1302
1303 A rarely known Python fact is that exceptions must conform to some
1304 simple rules to support being serialized by the pickle module.
1305
1306 Tasks that raise exceptions that aren't pickleable won't work
1307 properly when Pickle is used as the serializer.
1308
1309 To make sure that your exceptions are pickleable the exception
1310 *MUST* provide the original arguments it was instantiated
1311 with in its ``.args`` attribute. The simplest way
1312 to ensure this is to have the exception call ``Exception.__init__``.
1313
1314 Let's look at some examples that work, and one that doesn't:
1315
1316 .. code-block:: python
1317
1318
1319 # OK:
1320 class HttpError(Exception):
1321 pass
1322
1323 # BAD:
1324 class HttpError(Exception):
1325
1326 def __init__(self, status_code):
1327 self.status_code = status_code
1328
1329 # OK:
1330 class HttpError(Exception):
1331
1332 def __init__(self, status_code):
1333 self.status_code = status_code
1334 Exception.__init__(self, status_code) # <-- REQUIRED
1335
1336
1337 So the rule is:
1338 For any exception that supports custom arguments ``*args``,
1339 ``Exception.__init__(self, *args)`` must be used.
1340
1341 There's no special support for *keyword arguments*, so if you
1342 want to preserve keyword arguments when the exception is unpickled
1343 you have to pass them as regular args:
1344
1345 .. code-block:: python
1346
1347 class HttpError(Exception):
1348
1349 def __init__(self, status_code, headers=None, body=None):
1350 self.status_code = status_code
1351 self.headers = headers
1352 self.body = body
1353
1354 super(HttpError, self).__init__(status_code, headers, body)
1355
1356 .. _task-semipredicates:
1357
1358 Semipredicates
1359 ==============
1360
1361 The worker wraps the task in a tracing function that records the final
1362 state of the task. There are a number of exceptions that can be used to
1363 signal this function to change how it treats the return of the task.
1364
1365 .. _task-semipred-ignore:
1366
1367 Ignore
1368 ------
1369
1370 The task may raise :exc:`~@Ignore` to force the worker to ignore the
1371 task. This means that no state will be recorded for the task, but the
1372 message is still acknowledged (removed from queue).
1373
1374 This can be used if you want to implement custom revoke-like
1375 functionality, or manually store the result of a task.
1376
1377 Example keeping revoked tasks in a Redis set:
1378
1379 .. code-block:: python
1380
1381 from celery.exceptions import Ignore
1382
1383 @app.task(bind=True)
1384 def some_task(self):
1385 if redis.ismember('tasks.revoked', self.request.id):
1386 raise Ignore()
1387
1388 Example that stores results manually:
1389
1390 .. code-block:: python
1391
1392 from celery import states
1393 from celery.exceptions import Ignore
1394
1395 @app.task(bind=True)
1396 def get_tweets(self, user):
1397 timeline = twitter.get_timeline(user)
1398 if not self.request.called_directly:
1399 self.update_state(state=states.SUCCESS, meta=timeline)
1400 raise Ignore()
1401
1402 .. _task-semipred-reject:
1403
1404 Reject
1405 ------
1406
1407 The task may raise :exc:`~@Reject` to reject the task message using
1408 AMQPs ``basic_reject`` method. This won't have any effect unless
1409 :attr:`Task.acks_late` is enabled.
1410
1411 Rejecting a message has the same effect as acking it, but some
1412 brokers may implement additional functionality that can be used.
1413 For example RabbitMQ supports the concept of `Dead Letter Exchanges`_
1414 where a queue can be configured to use a dead letter exchange that rejected
1415 messages are redelivered to.
1416
1417 .. _`Dead Letter Exchanges`: http://www.rabbitmq.com/dlx.html
1418
1419 Reject can also be used to re-queue messages, but please be very careful
1420 when using this as it can easily result in an infinite message loop.
1421
1422 Example using reject when a task causes an out of memory condition:
1423
1424 .. code-block:: python
1425
1426 import errno
1427 from celery.exceptions import Reject
1428
1429 @app.task(bind=True, acks_late=True)
1430 def render_scene(self, path):
1431 file = get_file(path)
1432 try:
1433 renderer.render_scene(file)
1434
1435 # if the file is too big to fit in memory
1436 # we reject it so that it's redelivered to the dead letter exchange
1437 # and we can manually inspect the situation.
1438 except MemoryError as exc:
1439 raise Reject(exc, requeue=False)
1440 except OSError as exc:
1441 if exc.errno == errno.ENOMEM:
1442 raise Reject(exc, requeue=False)
1443
1444 # For any other error we retry after 10 seconds.
1445 except Exception as exc:
1446 raise self.retry(exc, countdown=10)
1447
1448 Example re-queuing the message:
1449
1450 .. code-block:: python
1451
1452 from celery.exceptions import Reject
1453
1454 @app.task(bind=True, acks_late=True)
1455 def requeues(self):
1456 if not self.request.delivery_info['redelivered']:
1457 raise Reject('no reason', requeue=True)
1458 print('received two times')
1459
1460 Consult your broker documentation for more details about the ``basic_reject``
1461 method.
1462
1463
1464 .. _task-semipred-retry:
1465
1466 Retry
1467 -----
1468
1469 The :exc:`~@Retry` exception is raised by the ``Task.retry`` method
1470 to tell the worker that the task is being retried.
1471
1472 .. _task-custom-classes:
1473
1474 Custom task classes
1475 ===================
1476
1477 All tasks inherit from the :class:`@Task` class.
1478 The :meth:`[email protected]` method becomes the task body.
1479
1480 As an example, the following code,
1481
1482 .. code-block:: python
1483
1484 @app.task
1485 def add(x, y):
1486 return x + y
1487
1488
1489 will do roughly this behind the scenes:
1490
1491 .. code-block:: python
1492
1493 class _AddTask(app.Task):
1494
1495 def run(self, x, y):
1496 return x + y
1497 add = app.tasks[_AddTask.name]
1498
1499
1500 Instantiation
1501 -------------
1502
1503 A task is **not** instantiated for every request, but is registered
1504 in the task registry as a global instance.
1505
1506 This means that the ``__init__`` constructor will only be called
1507 once per process, and that the task class is semantically closer to an
1508 Actor.
1509
1510 If you have a task,
1511
1512 .. code-block:: python
1513
1514 from celery import Task
1515
1516 class NaiveAuthenticateServer(Task):
1517
1518 def __init__(self):
1519 self.users = {'george': 'password'}
1520
1521 def run(self, username, password):
1522 try:
1523 return self.users[username] == password
1524 except KeyError:
1525 return False
1526
1527 And you route every request to the same process, then it
1528 will keep state between requests.
1529
1530 This can also be useful to cache resources,
1531 For example, a base Task class that caches a database connection:
1532
1533 .. code-block:: python
1534
1535 from celery import Task
1536
1537 class DatabaseTask(Task):
1538 _db = None
1539
1540 @property
1541 def db(self):
1542 if self._db is None:
1543 self._db = Database.connect()
1544 return self._db
1545
1546 Per task usage
1547 ~~~~~~~~~~~~~~
1548
1549 The above can be added to each task like this:
1550
1551 .. code-block:: python
1552
1553
1554 from celery.app import task
1555
1556 @app.task(base=DatabaseTask, bind=True)
1557 def process_rows(self: task):
1558 for row in self.db.table.all():
1559 process_row(row)
1560
1561 The ``db`` attribute of the ``process_rows`` task will then
1562 always stay the same in each process.
1563
1564 .. _custom-task-cls-app-wide:
1565
1566 App-wide usage
1567 ~~~~~~~~~~~~~~
1568
1569 You can also use your custom class in your whole Celery app by passing it as
1570 the ``task_cls`` argument when instantiating the app. This argument should be
1571 either a string giving the python path to your Task class or the class itself:
1572
1573 .. code-block:: python
1574
1575 from celery import Celery
1576
1577 app = Celery('tasks', task_cls='your.module.path:DatabaseTask')
1578
1579 This will make all your tasks declared using the decorator syntax within your
1580 app to use your ``DatabaseTask`` class and will all have a ``db`` attribute.
1581
1582 The default value is the class provided by Celery: ``'celery.app.task:Task'``.
1583
1584 Handlers
1585 --------
1586
1587 Task handlers are methods that execute at specific points in a task's lifecycle.
1588 All handlers run **synchronously** within the same worker process and thread
1589 that executes the task.
1590
1591 Execution timeline
1592 ~~~~~~~~~~~~~~~~~~
1593
1594 The following diagram shows the exact order of execution:
1595
1596 .. code-block:: text
1597
1598 Worker Process Timeline
1599 ┌───────────────────────────────────────────────────────────────┐
1600 │ 1. before_start() ← Blocks until complete │
1601 │ 2. run() ← Your task function │
1602 │ 3. [Result Backend] ← State + return value persisted │
1603 │ 4. on_success() OR ← Outcome-specific handler │
1604 │ on_retry() OR │ │
1605 │ on_failure() │ │
1606 │ 5. after_return() ← Runs last on terminal states │
1607 │ (skipped for RETRY/REJECTED/IGNORED) │
1608 └───────────────────────────────────────────────────────────────┘
1609
1610 .. important::
1611
1612 **Key points:**
1613
1614 - All handlers run in the **same worker process** as your task
1615 - ``before_start`` **blocks** the task - ``run()`` won't start until it completes
1616 - Result backend is updated **before** ``on_success``/``on_failure`` - other clients can see the task as finished while handlers are still running
1617 - ``after_return`` executes when the task reaches a terminal state.
1618 It does not run for ``RETRY``, ``REJECTED``, or ``IGNORED``. If you need
1619 a hook that fires on every attempt, use the :signal:`task_postrun` signal.
1620
1621 Available handlers
1622 ~~~~~~~~~~~~~~~~~~
1623
1624 .. method:: before_start(self, task_id, args, kwargs)
1625
1626 Run by the worker before the task starts executing.
1627
1628 .. note::
1629 This handler **blocks** the task: the :py:meth:`run` method will *not* begin
1630 until ``before_start`` returns.
1631
1632 .. versionadded:: 5.2
1633
1634 :param task_id: Unique id of the task to execute.
1635 :param args: Original arguments for the task to execute.
1636 :param kwargs: Original keyword arguments for the task to execute.
1637
1638 The return value of this handler is ignored.
1639
1640 .. method:: on_success(self, retval, task_id, args, kwargs)
1641
1642 Success handler.
1643
1644 Run by the worker if the task executes successfully.
1645
1646 .. note::
1647 Invoked **after** the task result has already been persisted in the
1648 result backend. External clients may observe the task as ``SUCCESS``
1649 while this handler is still running.
1650
1651 :param retval: The return value of the task.
1652 :param task_id: Unique id of the executed task.
1653 :param args: Original arguments for the executed task.
1654 :param kwargs: Original keyword arguments for the executed task.
1655
1656 The return value of this handler is ignored.
1657
1658 .. method:: on_retry(self, exc, task_id, args, kwargs, einfo)
1659
1660 Retry handler.
1661
1662 Run by the worker when the task is to be retried.
1663
1664 .. note::
1665 Invoked **after** the task state has been updated to ``RETRY`` in the
1666 result backend but **before** the retry is scheduled.
1667
1668 :param exc: The exception sent to :meth:`retry`.
1669 :param task_id: Unique id of the retried task.
1670 :param args: Original arguments for the retried task.
1671 :param kwargs: Original keyword arguments for the retried task.
1672 :param einfo: :class:`~billiard.einfo.ExceptionInfo` instance.
1673
1674 The return value of this handler is ignored.
1675
1676 .. method:: on_failure(self, exc, task_id, args, kwargs, einfo)
1677
1678 Failure handler.
1679
1680 Run by the worker when the task fails.
1681
1682 .. note::
1683 Invoked **after** the task result has already been persisted in the
1684 result backend with ``FAILURE`` state. External clients may observe
1685 the task as failed while this handler is still running.
1686
1687 :param exc: The exception raised by the task.
1688 :param task_id: Unique id of the failed task.
1689 :param args: Original arguments for the failed task.
1690 :param kwargs: Original keyword arguments for the failed task.
1691 :param einfo: :class:`~billiard.einfo.ExceptionInfo` instance.
1692
1693 The return value of this handler is ignored.
1694
1695 .. method:: after_return(self, status, retval, task_id, args, kwargs, einfo)
1696
1697 Handler called after the task returns.
1698
1699 .. note::
1700 Executes after the outcome-specific handler when the task reaches a
1701 terminal state.
1702
1703 In practice, this means it runs after ``on_success`` or ``on_failure``.
1704 It is not executed for ``RETRY``, ``REJECTED``, or ``IGNORED`` states.
1705 If a hook is needed for every attempt, consider using the
1706 :signal:`task_postrun` signal.
1707
1708 :param status: Current task state.
1709 :param retval: Task return value/exception.
1710 :param task_id: Unique id of the task.
1711 :param args: Original arguments for the task that returned.
1712 :param kwargs: Original keyword arguments for the task that returned.
1713 :param einfo: :class:`~billiard.einfo.ExceptionInfo` instance.
1714
1715 The return value of this handler is ignored.
1716
1717 Example usage
1718 ~~~~~~~~~~~~~
1719
1720 .. code-block:: python
1721
1722 import time
1723 from celery import Task
1724
1725 class MyTask(Task):
1726
1727 def before_start(self, task_id, args, kwargs):
1728 print(f"Task {task_id} starting with args {args}")
1729 # This blocks - run() won't start until this returns
1730
1731 def on_success(self, retval, task_id, args, kwargs):
1732 print(f"Task {task_id} succeeded with result: {retval}")
1733 # Result is already visible to clients at this point
1734
1735 def on_failure(self, exc, task_id, args, kwargs, einfo):
1736 print(f"Task {task_id} failed: {exc}")
1737 # Task state is already FAILURE in backend
1738
1739 def after_return(self, status, retval, task_id, args, kwargs, einfo):
1740 print(f"Task {task_id} finished with status: {status}")
1741 # Always runs last
1742
1743 @app.task(base=MyTask)
1744 def my_task(x, y):
1745 return x + y
1746
1747 .. _task-requests-and-custom-requests:
1748
1749 Requests and custom requests
1750 ----------------------------
1751
1752 Upon receiving a message to run a task, the `worker <guide-workers>`:ref:
1753 creates a `request <celery.worker.request.Request>`:class: to represent such
1754 demand.
1755
1756 Custom task classes may override which request class to use by changing the
1757 attribute `celery.app.task.Task.Request`:attr:. You may either assign the
1758 custom request class itself, or its fully qualified name.
1759
1760 The request has several responsibilities. Custom request classes should cover
1761 them all -- they are responsible to actually run and trace the task. We
1762 strongly recommend to inherit from `celery.worker.request.Request`:class:.
1763
1764 When using the `pre-forking worker <worker-concurrency>`:ref:, the methods
1765 `~celery.worker.request.Request.on_timeout`:meth: and
1766 `~celery.worker.request.Request.on_failure`:meth: are executed in the main
1767 worker process. An application may leverage such facility to detect failures
1768 which are not detected using `celery.app.task.Task.on_failure`:meth:.
1769
1770 As an example, the following custom request detects and logs hard time
1771 limits, and other failures.
1772
1773 .. code-block:: python
1774
1775 import logging
1776 from celery import Task
1777 from celery.worker.request import Request
1778
1779 logger = logging.getLogger('my.package')
1780
1781 class MyRequest(Request):
1782 'A minimal custom request to log failures and hard time limits.'
1783
1784 def on_timeout(self, soft, timeout):
1785 super(MyRequest, self).on_timeout(soft, timeout)
1786 if not soft:
1787 logger.warning(
1788 'A hard timeout was enforced for task %s',
1789 self.task.name
1790 )
1791
1792 def on_failure(self, exc_info, send_failed_event=True, return_ok=False):
1793 super().on_failure(
1794 exc_info,
1795 send_failed_event=send_failed_event,
1796 return_ok=return_ok
1797 )
1798 logger.warning(
1799 'Failure detected for task %s',
1800 self.task.name
1801 )
1802
1803 class MyTask(Task):
1804 Request = MyRequest # you can use a FQN 'my.package:MyRequest'
1805
1806 @app.task(base=MyTask)
1807 def some_longrunning_task():
1808 # use your imagination
1809
1810
1811 .. _task-how-they-work:
1812
1813 How it works
1814 ============
1815
1816 Here come the technical details. This part isn't something you need to know,
1817 but you may be interested.
1818
1819 All defined tasks are listed in a registry. The registry contains
1820 a list of task names and their task classes. You can investigate this registry
1821 yourself:
1822
1823 .. code-block:: pycon
1824
1825 >>> from proj.celery import app
1826 >>> app.tasks
1827 {'celery.chord_unlock':
1828 <@task: celery.chord_unlock>,
1829 'celery.backend_cleanup':
1830 <@task: celery.backend_cleanup>,
1831 'celery.chord':
1832 <@task: celery.chord>}
1833
1834 This is the list of tasks built into Celery. Note that tasks
1835 will only be registered when the module they're defined in is imported.
1836
1837 The default loader imports any modules listed in the
1838 :setting:`imports` setting.
1839
1840 The :meth:`@task` decorator is responsible for registering your task
1841 in the applications task registry.
1842
1843 When tasks are sent, no actual function code is sent with it, just the name
1844 of the task to execute. When the worker then receives the message it can look
1845 up the name in its task registry to find the execution code.
1846
1847 This means that your workers should always be updated with the same software
1848 as the client. This is a drawback, but the alternative is a technical
1849 challenge that's yet to be solved.
1850
1851 .. _task-best-practices:
1852
1853 Tips and Best Practices
1854 =======================
1855
1856 .. _task-ignore_results:
1857
1858 Ignore results you don't want
1859 -----------------------------
1860
1861 If you don't care about the results of a task, be sure to set the
1862 :attr:`[email protected]_result` option, as storing results
1863 wastes time and resources.
1864
1865 .. code-block:: python
1866
1867 @app.task(ignore_result=True)
1868 def mytask():
1869 something()
1870
1871 Results can even be disabled globally using the :setting:`task_ignore_result`
1872 setting.
1873
1874 .. versionadded::4.2
1875
1876 Results can be enabled/disabled on a per-execution basis, by passing the ``ignore_result`` boolean parameter,
1877 when calling ``apply_async``.
1878
1879 .. code-block:: python
1880
1881 @app.task
1882 def mytask(x, y):
1883 return x + y
1884
1885 # No result will be stored
1886 result = mytask.apply_async((1, 2), ignore_result=True)
1887 print(result.get()) # -> None
1888
1889 # Result will be stored
1890 result = mytask.apply_async((1, 2), ignore_result=False)
1891 print(result.get()) # -> 3
1892
1893 By default tasks will *not ignore results* (``ignore_result=False``) when a result backend is configured.
1894
1895
1896 The option precedence order is the following:
1897
1898 1. Global :setting:`task_ignore_result`
1899 2. :attr:`[email protected]_result` option
1900 3. Task execution option ``ignore_result``
1901
1902 More optimization tips
1903 ----------------------
1904
1905 You find additional optimization tips in the
1906 :ref:`Optimizing Guide <guide-optimizing>`.
1907
1908 .. _task-synchronous-subtasks:
1909
1910 Avoid launching synchronous subtasks
1911 ------------------------------------
1912
1913 Having a task wait for the result of another task is really inefficient,
1914 and may even cause a deadlock if the worker pool is exhausted.
1915
1916 Make your design asynchronous instead, for example by using *callbacks*.
1917
1918 **Bad**:
1919
1920 .. code-block:: python
1921
1922 @app.task
1923 def update_page_info(url):
1924 page = fetch_page.delay(url).get()
1925 info = parse_page.delay(page).get()
1926 store_page_info.delay(url, info)
1927
1928 @app.task
1929 def fetch_page(url):
1930 return myhttplib.get(url)
1931
1932 @app.task
1933 def parse_page(page):
1934 return myparser.parse_document(page)
1935
1936 @app.task
1937 def store_page_info(url, info):
1938 return PageInfo.objects.create(url, info)
1939
1940
1941 **Good**:
1942
1943 .. code-block:: python
1944
1945 def update_page_info(url):
1946 # fetch_page -> parse_page -> store_page
1947 chain = fetch_page.s(url) | parse_page.s() | store_page_info.s(url)
1948 chain()
1949
1950 @app.task()
1951 def fetch_page(url):
1952 return myhttplib.get(url)
1953
1954 @app.task()
1955 def parse_page(page):
1956 return myparser.parse_document(page)
1957
1958 @app.task(ignore_result=True)
1959 def store_page_info(info, url):
1960 PageInfo.objects.create(url=url, info=info)
1961
1962
1963 Here I instead created a chain of tasks by linking together
1964 different :func:`~celery.signature`'s.
1965 You can read about chains and other powerful constructs
1966 at :ref:`designing-workflows`.
1967
1968 By default Celery will not allow you to run subtasks synchronously within a task,
1969 but in rare or extreme cases you might need to do so.
1970 **WARNING**:
1971 enabling subtasks to run synchronously is not recommended!
1972
1973 .. code-block:: python
1974
1975 @app.task
1976 def update_page_info(url):
1977 page = fetch_page.delay(url).get(disable_sync_subtasks=False)
1978 info = parse_page.delay(page).get(disable_sync_subtasks=False)
1979 store_page_info.delay(url, info)
1980
1981 @app.task
1982 def fetch_page(url):
1983 return myhttplib.get(url)
1984
1985 @app.task
1986 def parse_page(page):
1987 return myparser.parse_document(page)
1988
1989 @app.task
1990 def store_page_info(url, info):
1991 return PageInfo.objects.create(url, info)
1992
1993
1994 .. _task-performance-and-strategies:
1995
1996 Performance and Strategies
1997 ==========================
1998
1999 .. _task-granularity:
2000
2001 Granularity
2002 -----------
2003
2004 The task granularity is the amount of computation needed by each subtask.
2005 In general it is better to split the problem up into many small tasks rather
2006 than have a few long running tasks.
2007
2008 With smaller tasks you can process more tasks in parallel and the tasks
2009 won't run long enough to block the worker from processing other waiting tasks.
2010
2011 However, executing a task does have overhead. A message needs to be sent, data
2012 may not be local, etc. So if the tasks are too fine-grained the
2013 overhead added probably removes any benefit.
2014
2015 .. seealso::
2016
2017 The book `Art of Concurrency`_ has a section dedicated to the topic
2018 of task granularity [AOC1]_.
2019
2020 .. _`Art of Concurrency`: http://oreilly.com/catalog/9780596521547
2021
2022 .. [AOC1] Breshears, Clay. Section 2.2.1, "The Art of Concurrency".
2023 O'Reilly Media, Inc. May 15, 2009. ISBN-13 978-0-596-52153-0.
2024
2025 .. _task-data-locality:
2026
2027 Data locality
2028 -------------
2029
2030 The worker processing the task should be as close to the data as
2031 possible. The best would be to have a copy in memory, the worst would be a
2032 full transfer from another continent.
2033
2034 If the data is far away, you could try to run another worker at location, or
2035 if that's not possible - cache often used data, or preload data you know
2036 is going to be used.
2037
2038 The easiest way to share data between workers is to use a distributed cache
2039 system, like `memcached`_.
2040
2041 .. seealso::
2042
2043 The paper `Distributed Computing Economics`_ by Jim Gray is an excellent
2044 introduction to the topic of data locality.
2045
2046 .. _`Distributed Computing Economics`:
2047 http://research.microsoft.com/pubs/70001/tr-2003-24.pdf
2048
2049 .. _`memcached`: http://memcached.org/
2050
2051 .. _task-state:
2052
2053 State
2054 -----
2055
2056 Since Celery is a distributed system, you can't know which process, or
2057 on what machine the task will be executed. You can't even know if the task will
2058 run in a timely manner.
2059
2060 The ancient async sayings tells us that “asserting the world is the
2061 responsibility of the task”. What this means is that the world view may
2062 have changed since the task was requested, so the task is responsible for
2063 making sure the world is how it should be; If you have a task
2064 that re-indexes a search engine, and the search engine should only be
2065 re-indexed at maximum every 5 minutes, then it must be the tasks
2066 responsibility to assert that, not the callers.
2067
2068 Another gotcha is Django model objects. They shouldn't be passed on as
2069 arguments to tasks. It's almost always better to re-fetch the object from
2070 the database when the task is running instead, as using old data may lead
2071 to race conditions.
2072
2073 Imagine the following scenario where you have an article and a task
2074 that automatically expands some abbreviations in it:
2075
2076 .. code-block:: python
2077
2078 class Article(models.Model):
2079 title = models.CharField()
2080 body = models.TextField()
2081
2082 @app.task
2083 def expand_abbreviations(article):
2084 article.body.replace('MyCorp', 'My Corporation')
2085 article.save()
2086
2087 First, an author creates an article and saves it, then the author
2088 clicks on a button that initiates the abbreviation task:
2089
2090 .. code-block:: pycon
2091
2092 >>> article = Article.objects.get(id=102)
2093 >>> expand_abbreviations.delay(article)
2094
2095 Now, the queue is very busy, so the task won't be run for another 2 minutes.
2096 In the meantime another author makes changes to the article, so
2097 when the task is finally run, the body of the article is reverted to the old
2098 version because the task had the old body in its argument.
2099
2100 Fixing the race condition is easy, just use the article id instead, and
2101 re-fetch the article in the task body:
2102
2103 .. code-block:: python
2104
2105 @app.task
2106 def expand_abbreviations(article_id):
2107 article = Article.objects.get(id=article_id)
2108 article.body.replace('MyCorp', 'My Corporation')
2109 article.save()
2110
2111 .. code-block:: pycon
2112
2113 >>> expand_abbreviations.delay(article_id)
2114
2115 There might even be performance benefits to this approach, as sending large
2116 messages may be expensive.
2117
2118 .. _task-database-transactions:
2119
2120 Database transactions
2121 ---------------------
2122
2123 Let's have a look at another example:
2124
2125 .. code-block:: python
2126
2127 from django.db import transaction
2128 from django.http import HttpResponseRedirect
2129
2130 @transaction.atomic
2131 def create_article(request):
2132 article = Article.objects.create()
2133 expand_abbreviations.delay(article.pk)
2134 return HttpResponseRedirect('/articles/')
2135
2136 This is a Django view creating an article object in the database,
2137 then passing the primary key to a task. It uses the `transaction.atomic`
2138 decorator, that will commit the transaction when the view returns, or
2139 roll back if the view raises an exception.
2140
2141 There is a race condition because transactions are atomic. This means the article object is not persisted to the database until after the view function returns a response. If the asynchronous task starts executing before the transaction is committed, it may attempt to query the article object before it exists. To prevent this, we need to ensure that the transaction is committed before triggering the task.
2142
2143 The solution is to use
2144 :meth:`~celery.contrib.django.task.DjangoTask.delay_on_commit` instead:
2145
2146 .. code-block:: python
2147
2148 from django.db import transaction
2149 from django.http import HttpResponseRedirect
2150
2151 @transaction.atomic
2152 def create_article(request):
2153 article = Article.objects.create()
2154 expand_abbreviations.delay_on_commit(article.pk)
2155 return HttpResponseRedirect('/articles/')
2156
2157 This method was added in Celery 5.4. It's a shortcut that uses Django's
2158 ``on_commit`` callback to launch your Celery task once all transactions
2159 have been committed successfully.
2160
2161 With Celery <5.4
2162 ~~~~~~~~~~~~~~~~
2163
2164 If you're using an older version of Celery, you can replicate this behaviour
2165 using the Django callback directly as follows:
2166
2167 .. code-block:: python
2168
2169 import functools
2170 from django.db import transaction
2171 from django.http import HttpResponseRedirect
2172
2173 @transaction.atomic
2174 def create_article(request):
2175 article = Article.objects.create()
2176 transaction.on_commit(
2177 functools.partial(expand_abbreviations.delay, article.pk)
2178 )
2179 return HttpResponseRedirect('/articles/')
2180
2181 .. note::
2182 ``on_commit`` is available in Django 1.9 and above, if you are using a
2183 version prior to that then the `django-transaction-hooks`_ library
2184 adds support for this.
2185
2186 .. _`django-transaction-hooks`: https://github.com/carljm/django-transaction-hooks
2187
2188 .. _task-example:
2189
2190 Example
2191 =======
2192
2193 Let's take a real world example: a blog where comments posted need to be
2194 filtered for spam. When the comment is created, the spam filter runs in the
2195 background, so the user doesn't have to wait for it to finish.
2196
2197 I have a Django blog application allowing comments
2198 on blog posts. I'll describe parts of the models/views and tasks for this
2199 application.
2200
2201 ``blog/models.py``
2202 ------------------
2203
2204 The comment model looks like this:
2205
2206 .. code-block:: python
2207
2208 from django.db import models
2209 from django.utils.translation import ugettext_lazy as _
2210
2211
2212 class Comment(models.Model):
2213 name = models.CharField(_('name'), max_length=64)
2214 email_address = models.EmailField(_('email address'))
2215 homepage = models.URLField(_('home page'),
2216 blank=True, verify_exists=False)
2217 comment = models.TextField(_('comment'))
2218 pub_date = models.DateTimeField(_('Published date'),
2219 editable=False, auto_add_now=True)
2220 is_spam = models.BooleanField(_('spam?'),
2221 default=False, editable=False)
2222
2223 class Meta:
2224 verbose_name = _('comment')
2225 verbose_name_plural = _('comments')
2226
2227
2228 In the view where the comment is posted, I first write the comment
2229 to the database, then I launch the spam filter task in the background.
2230
2231 .. _task-example-blog-views:
2232
2233 ``blog/views.py``
2234 -----------------
2235
2236 .. code-block:: python
2237
2238 from django import forms
2239 from django.http import HttpResponseRedirect
2240 from django.template.context import RequestContext
2241 from django.shortcuts import get_object_or_404, render_to_response
2242
2243 from blog import tasks
2244 from blog.models import Comment
2245
2246
2247 class CommentForm(forms.ModelForm):
2248
2249 class Meta:
2250 model = Comment
2251
2252
2253 def add_comment(request, slug, template_name='comments/create.html'):
2254 post = get_object_or_404(Entry, slug=slug)
2255 remote_addr = request.META.get('REMOTE_ADDR')
2256
2257 if request.method == 'post':
2258 form = CommentForm(request.POST, request.FILES)
2259 if form.is_valid():
2260 comment = form.save()
2261 # Check spam asynchronously.
2262 tasks.spam_filter.delay(comment_id=comment.id,
2263 remote_addr=remote_addr)
2264 return HttpResponseRedirect(post.get_absolute_url())
2265 else:
2266 form = CommentForm()
2267
2268 context = RequestContext(request, {'form': form})
2269 return render_to_response(template_name, context_instance=context)
2270
2271
2272 To filter spam in comments I use `Akismet`_, the service
2273 used to filter spam in comments posted to the free blog platform
2274 `Wordpress`. `Akismet`_ is free for personal use, but for commercial use you
2275 need to pay. You have to sign up to their service to get an API key.
2276
2277 To make API calls to `Akismet`_ I use the `akismet.py`_ library written by
2278 `Michael Foord`_.
2279
2280 .. _task-example-blog-tasks:
2281
2282 ``blog/tasks.py``
2283 -----------------
2284
2285 .. code-block:: python
2286
2287 from celery import Celery
2288
2289 from akismet import Akismet
2290
2291 from django.core.exceptions import ImproperlyConfigured
2292 from django.contrib.sites.models import Site
2293
2294 from blog.models import Comment
2295
2296
2297 app = Celery(broker='amqp://')
2298
2299
2300 @app.task
2301 def spam_filter(comment_id, remote_addr=None):
2302 logger = spam_filter.get_logger()
2303 logger.info('Running spam filter for comment %s', comment_id)
2304
2305 comment = Comment.objects.get(pk=comment_id)
2306 current_domain = Site.objects.get_current().domain
2307 akismet = Akismet(settings.AKISMET_KEY, 'http://{0}'.format(domain))
2308 if not akismet.verify_key():
2309 raise ImproperlyConfigured('Invalid AKISMET_KEY')
2310
2311
2312 is_spam = akismet.comment_check(user_ip=remote_addr,
2313 comment_content=comment.comment,
2314 comment_author=comment.name,
2315 comment_author_email=comment.email_address)
2316 if is_spam:
2317 comment.is_spam = True
2318 comment.save()
2319
2320 return is_spam
2321
2322 .. _`Akismet`: http://akismet.com/faq/
2323 .. _`akismet.py`: http://www.voidspace.org.uk/downloads/akismet.py
2324 .. _`Michael Foord`: http://www.voidspace.org.uk/
2325 .. _`exponential backoff`: https://en.wikipedia.org/wiki/Exponential_backoff
2326 .. _`jitter`: https://en.wikipedia.org/wiki/Jitter
2327 .. _`Pydantic`: https://docs.pydantic.dev/