| 1 |
.. _guide-calling: |
| 2 |
|
| 3 |
=============== |
| 4 |
Calling Tasks |
| 5 |
=============== |
| 6 |
|
| 7 |
.. contents:: |
| 8 |
:local: |
| 9 |
:depth: 1 |
| 10 |
|
| 11 |
|
| 12 |
.. _calling-basics: |
| 13 |
|
| 14 |
Basics |
| 15 |
====== |
| 16 |
|
| 17 |
This document describes Celery's uniform "Calling API" |
| 18 |
used by task instances and the :ref:`canvas <guide-canvas>`. |
| 19 |
|
| 20 |
The API defines a standard set of execution options, as well as three methods: |
| 21 |
|
| 22 |
- ``apply_async(args[, kwargs[, …]])`` |
| 23 |
|
| 24 |
Sends a task message. |
| 25 |
|
| 26 |
- ``delay(*args, **kwargs)`` |
| 27 |
|
| 28 |
Shortcut to send a task message, but doesn't support execution |
| 29 |
options. |
| 30 |
|
| 31 |
- *calling* (``__call__``) |
| 32 |
|
| 33 |
Applying an object supporting the calling API (e.g., ``add(2, 2)``) |
| 34 |
means that the task will not be executed by a worker, but in the current |
| 35 |
process instead (a message won't be sent). |
| 36 |
|
| 37 |
.. _calling-cheat: |
| 38 |
|
| 39 |
.. topic:: Quick Cheat Sheet |
| 40 |
|
| 41 |
- ``T.delay(arg, kwarg=value)`` |
| 42 |
Star arguments shortcut to ``.apply_async``. |
| 43 |
(``.delay(*args, **kwargs)`` calls ``.apply_async(args, kwargs)``). |
| 44 |
|
| 45 |
- ``T.apply_async((arg,), {'kwarg': value})`` |
| 46 |
|
| 47 |
- ``T.apply_async(countdown=10)`` |
| 48 |
executes in 10 seconds from now. |
| 49 |
|
| 50 |
- ``T.apply_async(eta=now + timedelta(seconds=10))`` |
| 51 |
executes in 10 seconds from now, specified using ``eta`` |
| 52 |
|
| 53 |
- ``T.apply_async(countdown=60, expires=120)`` |
| 54 |
executes in one minute from now, but expires after 2 minutes. |
| 55 |
|
| 56 |
- ``T.apply_async(expires=now + timedelta(days=2))`` |
| 57 |
expires in 2 days, set using :class:`~datetime.datetime`. |
| 58 |
|
| 59 |
- ``T.apply_async(task_id=f'my_own_task_id')`` |
| 60 |
sets the id of the task to my_own_task_id instead of a uuid that is normally generated |
| 61 |
|
| 62 |
Example |
| 63 |
------- |
| 64 |
|
| 65 |
The :meth:`[email protected]` method is convenient as it looks like calling a regular |
| 66 |
function: |
| 67 |
|
| 68 |
.. code-block:: python |
| 69 |
|
| 70 |
task.delay(arg1, arg2, kwarg1='x', kwarg2='y') |
| 71 |
|
| 72 |
Using :meth:`[email protected]_async` instead you have to write: |
| 73 |
|
| 74 |
.. code-block:: python |
| 75 |
|
| 76 |
task.apply_async(args=[arg1, arg2], kwargs={'kwarg1': 'x', 'kwarg2': 'y'}) |
| 77 |
|
| 78 |
.. sidebar:: Tip |
| 79 |
|
| 80 |
If the task isn't registered in the current process |
| 81 |
you can use :meth:`~@send_task` to call the task by name instead. |
| 82 |
|
| 83 |
|
| 84 |
So `delay` is clearly convenient, but if you want to set additional execution |
| 85 |
options you have to use ``apply_async``. |
| 86 |
|
| 87 |
The rest of this document will go into the task execution |
| 88 |
options in detail. All examples use a task |
| 89 |
called `add`, returning the sum of two arguments: |
| 90 |
|
| 91 |
.. code-block:: python |
| 92 |
|
| 93 |
@app.task |
| 94 |
def add(x, y): |
| 95 |
return x + y |
| 96 |
|
| 97 |
|
| 98 |
.. topic:: There's another way… |
| 99 |
|
| 100 |
You'll learn more about this later while reading about the :ref:`Canvas |
| 101 |
<guide-canvas>`, but :class:`~celery.signature`'s are objects used to pass around |
| 102 |
the signature of a task invocation, (for example to send it over the |
| 103 |
network), and they also support the Calling API: |
| 104 |
|
| 105 |
.. code-block:: python |
| 106 |
|
| 107 |
task.s(arg1, arg2, kwarg1='x', kwargs2='y').apply_async() |
| 108 |
|
| 109 |
.. _calling-links: |
| 110 |
|
| 111 |
Linking (callbacks/errbacks) |
| 112 |
============================ |
| 113 |
|
| 114 |
Celery supports linking tasks together so that one task follows another. |
| 115 |
The callback task will be applied with the result of the parent task |
| 116 |
as a partial argument: |
| 117 |
|
| 118 |
.. code-block:: python |
| 119 |
|
| 120 |
add.apply_async((2, 2), link=add.s(16)) |
| 121 |
|
| 122 |
.. sidebar:: What's ``s``? |
| 123 |
|
| 124 |
The ``add.s`` call used here is called a signature. If you |
| 125 |
don't know what they are you should read about them in the |
| 126 |
:ref:`canvas guide <guide-canvas>`. |
| 127 |
There you can also learn about :class:`~celery.chain`: a simpler |
| 128 |
way to chain tasks together. |
| 129 |
|
| 130 |
In practice the ``link`` execution option is considered an internal |
| 131 |
primitive, and you'll probably not use it directly, but |
| 132 |
use chains instead. |
| 133 |
|
| 134 |
Here the result of the first task (4) will be sent to a new |
| 135 |
task that adds 16 to the previous result, forming the expression |
| 136 |
:math:`(2 + 2) + 16 = 20` |
| 137 |
|
| 138 |
|
| 139 |
You can also cause a callback to be applied if task raises an exception |
| 140 |
(*errback*). The worker won't actually call the errback as a task, but will |
| 141 |
instead call the errback function directly so that the raw request, exception |
| 142 |
and traceback objects can be passed to it. |
| 143 |
|
| 144 |
This is an example error callback: |
| 145 |
|
| 146 |
.. code-block:: python |
| 147 |
|
| 148 |
@app.task |
| 149 |
def error_handler(request, exc, traceback): |
| 150 |
print('Task {0} raised exception: {1!r}\n{2!r}'.format( |
| 151 |
request.id, exc, traceback)) |
| 152 |
|
| 153 |
it can be added to the task using the ``link_error`` execution |
| 154 |
option: |
| 155 |
|
| 156 |
.. code-block:: python |
| 157 |
|
| 158 |
add.apply_async((2, 2), link_error=error_handler.s()) |
| 159 |
|
| 160 |
|
| 161 |
In addition, both the ``link`` and ``link_error`` options can be expressed |
| 162 |
as a list: |
| 163 |
|
| 164 |
.. code-block:: python |
| 165 |
|
| 166 |
add.apply_async((2, 2), link=[add.s(16), other_task.s()]) |
| 167 |
|
| 168 |
The callbacks/errbacks will then be called in order, and all |
| 169 |
callbacks will be called with the return value of the parent task |
| 170 |
as a partial argument. |
| 171 |
|
| 172 |
In the case of a chord, we can handle errors using multiple handling strategies. |
| 173 |
See :ref:`chord error handling <chord-errors>` for more information. |
| 174 |
|
| 175 |
.. _calling-on-message: |
| 176 |
|
| 177 |
On message |
| 178 |
========== |
| 179 |
|
| 180 |
Celery supports catching all states changes by setting on_message callback. |
| 181 |
|
| 182 |
For example for long-running tasks to send task progress you can do something like this: |
| 183 |
|
| 184 |
.. code-block:: python |
| 185 |
|
| 186 |
@app.task(bind=True) |
| 187 |
def hello(self, a, b): |
| 188 |
time.sleep(1) |
| 189 |
self.update_state(state="PROGRESS", meta={'progress': 50}) |
| 190 |
time.sleep(1) |
| 191 |
self.update_state(state="PROGRESS", meta={'progress': 90}) |
| 192 |
time.sleep(1) |
| 193 |
return 'hello world: %i' % (a+b) |
| 194 |
|
| 195 |
.. code-block:: python |
| 196 |
|
| 197 |
def on_raw_message(body): |
| 198 |
print(body) |
| 199 |
|
| 200 |
a, b = 1, 1 |
| 201 |
r = hello.apply_async(args=(a, b)) |
| 202 |
print(r.get(on_message=on_raw_message, propagate=False)) |
| 203 |
|
| 204 |
Will generate output like this: |
| 205 |
|
| 206 |
.. code-block:: text |
| 207 |
|
| 208 |
{'task_id': '5660d3a3-92b8-40df-8ccc-33a5d1d680d7', |
| 209 |
'result': {'progress': 50}, |
| 210 |
'children': [], |
| 211 |
'status': 'PROGRESS', |
| 212 |
'traceback': None} |
| 213 |
{'task_id': '5660d3a3-92b8-40df-8ccc-33a5d1d680d7', |
| 214 |
'result': {'progress': 90}, |
| 215 |
'children': [], |
| 216 |
'status': 'PROGRESS', |
| 217 |
'traceback': None} |
| 218 |
{'task_id': '5660d3a3-92b8-40df-8ccc-33a5d1d680d7', |
| 219 |
'result': 'hello world: 10', |
| 220 |
'children': [], |
| 221 |
'status': 'SUCCESS', |
| 222 |
'traceback': None} |
| 223 |
hello world: 10 |
| 224 |
|
| 225 |
|
| 226 |
.. _calling-eta: |
| 227 |
|
| 228 |
ETA and Countdown |
| 229 |
================= |
| 230 |
|
| 231 |
The ETA (estimated time of arrival) lets you set a specific date and time that |
| 232 |
is the earliest time at which your task will be executed. `countdown` is |
| 233 |
a shortcut to set ETA by seconds into the future. |
| 234 |
|
| 235 |
.. code-block:: pycon |
| 236 |
|
| 237 |
>>> result = add.apply_async((2, 2), countdown=3) |
| 238 |
>>> result.get() # this takes at least 3 seconds to return |
| 239 |
4 |
| 240 |
|
| 241 |
The task is guaranteed to be executed at some time *after* the |
| 242 |
specified date and time, but not necessarily at that exact time. |
| 243 |
Possible reasons for broken deadlines may include many items waiting |
| 244 |
in the queue, or heavy network latency. To make sure your tasks |
| 245 |
are executed in a timely manner you should monitor the queue for congestion. Use |
| 246 |
Munin, or similar tools, to receive alerts, so appropriate action can be |
| 247 |
taken to ease the workload. See :ref:`monitoring-munin`. |
| 248 |
|
| 249 |
While `countdown` is an integer, `eta` must be a :class:`~datetime.datetime` |
| 250 |
object, specifying an exact date and time (including millisecond precision, |
| 251 |
and timezone information): |
| 252 |
|
| 253 |
.. code-block:: pycon |
| 254 |
|
| 255 |
>>> from datetime import datetime, timedelta, timezone |
| 256 |
|
| 257 |
>>> tomorrow = datetime.now(timezone.utc) + timedelta(days=1) |
| 258 |
>>> add.apply_async((2, 2), eta=tomorrow) |
| 259 |
|
| 260 |
.. warning:: |
| 261 |
|
| 262 |
Tasks with `eta` or `countdown` are immediately fetched by the worker |
| 263 |
and until the scheduled time passes, they reside in the worker's memory. |
| 264 |
When using those options to schedule lots of tasks for a distant future, |
| 265 |
those tasks may accumulate in the worker and make a significant impact on |
| 266 |
the RAM usage. |
| 267 |
|
| 268 |
Moreover, tasks are not acknowledged until the worker starts executing |
| 269 |
them. If using Redis as a broker, task will get redelivered when `countdown` |
| 270 |
exceeds `visibility_timeout` (see :ref:`redis-caveats`). |
| 271 |
|
| 272 |
Therefore, using `eta` and `countdown` **is not recommended** for |
| 273 |
scheduling tasks for a distant future. Ideally, use values no longer |
| 274 |
than several minutes. For longer durations, consider using |
| 275 |
database-backed periodic tasks, e.g. with :pypi:`django-celery-beat` if |
| 276 |
using Django (see :ref:`beat-custom-schedulers`). |
| 277 |
|
| 278 |
.. warning:: |
| 279 |
|
| 280 |
When using RabbitMQ as a message broker when specifying a ``countdown`` |
| 281 |
over 15 minutes, you may encounter the problem that the worker terminates |
| 282 |
with an :exc:`~amqp.exceptions.PreconditionFailed` error will be raised: |
| 283 |
|
| 284 |
.. code-block:: pycon |
| 285 |
|
| 286 |
amqp.exceptions.PreconditionFailed: (0, 0): (406) PRECONDITION_FAILED - consumer ack timed out on channel |
| 287 |
|
| 288 |
In RabbitMQ since version 3.8.15 the default value for |
| 289 |
``consumer_timeout`` is 15 minutes. |
| 290 |
Since version 3.8.17 it was increased to 30 minutes. If a consumer does |
| 291 |
not ack its delivery for more than the timeout value, its channel will be |
| 292 |
closed with a ``PRECONDITION_FAILED`` channel exception. |
| 293 |
See `Delivery Acknowledgement Timeout`_ for more information. |
| 294 |
|
| 295 |
To solve the problem, in RabbitMQ configuration file ``rabbitmq.conf`` you |
| 296 |
should specify the ``consumer_timeout`` parameter greater than or equal to |
| 297 |
your countdown value. For example, you can specify a very large value |
| 298 |
of ``consumer_timeout = 31622400000``, which is equal to 1 year |
| 299 |
in milliseconds, to avoid problems in the future. |
| 300 |
|
| 301 |
.. _`Delivery Acknowledgement Timeout`: https://www.rabbitmq.com/consumers.html#acknowledgement-timeout |
| 302 |
|
| 303 |
.. _calling-expiration: |
| 304 |
|
| 305 |
Expiration |
| 306 |
========== |
| 307 |
|
| 308 |
The `expires` argument defines an optional expiry time, |
| 309 |
either as seconds after task publish, or a specific date and time using |
| 310 |
:class:`~datetime.datetime`: |
| 311 |
|
| 312 |
.. code-block:: pycon |
| 313 |
|
| 314 |
>>> # Task expires after one minute from now. |
| 315 |
>>> add.apply_async((10, 10), expires=60) |
| 316 |
|
| 317 |
>>> # Also supports datetime |
| 318 |
>>> from datetime import datetime, timedelta, timezone |
| 319 |
>>> add.apply_async((10, 10), kwargs, |
| 320 |
... expires=datetime.now(timezone.utc) + timedelta(days=1)) |
| 321 |
|
| 322 |
|
| 323 |
When a worker receives an expired task it will mark |
| 324 |
the task as :state:`REVOKED` (:exc:`~@TaskRevokedError`). |
| 325 |
|
| 326 |
.. _calling-retry: |
| 327 |
|
| 328 |
Message Sending Retry |
| 329 |
===================== |
| 330 |
|
| 331 |
Celery will automatically retry sending messages in the event of connection |
| 332 |
failure, and retry behavior can be configured -- like how often to retry, or a maximum |
| 333 |
number of retries -- or disabled all together. |
| 334 |
|
| 335 |
To disable retry you can set the ``retry`` execution option to :const:`False`: |
| 336 |
|
| 337 |
.. code-block:: python |
| 338 |
|
| 339 |
add.apply_async((2, 2), retry=False) |
| 340 |
|
| 341 |
.. topic:: Related Settings |
| 342 |
|
| 343 |
.. hlist:: |
| 344 |
:columns: 2 |
| 345 |
|
| 346 |
- :setting:`task_publish_retry` |
| 347 |
- :setting:`task_publish_retry_policy` |
| 348 |
|
| 349 |
Retry Policy |
| 350 |
------------ |
| 351 |
|
| 352 |
A retry policy is a mapping that controls how retries behave, |
| 353 |
and can contain the following keys: |
| 354 |
|
| 355 |
- `max_retries` |
| 356 |
|
| 357 |
Maximum number of retries before giving up, in this case the |
| 358 |
exception that caused the retry to fail will be raised. |
| 359 |
|
| 360 |
A value of :const:`None` means it will retry forever. |
| 361 |
|
| 362 |
The default is to retry 3 times. |
| 363 |
|
| 364 |
- `interval_start` |
| 365 |
|
| 366 |
Defines the number of seconds (float or integer) to wait between |
| 367 |
retries. Default is 0 (the first retry will be instantaneous). |
| 368 |
|
| 369 |
- `interval_step` |
| 370 |
|
| 371 |
On each consecutive retry this number will be added to the retry |
| 372 |
delay (float or integer). Default is 0.2. |
| 373 |
|
| 374 |
- `interval_max` |
| 375 |
|
| 376 |
Maximum number of seconds (float or integer) to wait between |
| 377 |
retries. Default is 0.2. |
| 378 |
|
| 379 |
- `retry_errors` |
| 380 |
|
| 381 |
`retry_errors` is a tuple of exception classes that should be retried. |
| 382 |
It will be ignored if not specified. Default is None (ignored). |
| 383 |
|
| 384 |
For example, if you want to retry only tasks that were timed out, you can use |
| 385 |
:exc:`~kombu.exceptions.TimeoutError`: |
| 386 |
|
| 387 |
.. code-block:: python |
| 388 |
|
| 389 |
from kombu.exceptions import TimeoutError |
| 390 |
|
| 391 |
add.apply_async((2, 2), retry=True, retry_policy={ |
| 392 |
'max_retries': 3, |
| 393 |
'retry_errors': (TimeoutError, ), |
| 394 |
}) |
| 395 |
|
| 396 |
.. versionadded:: 5.3 |
| 397 |
|
| 398 |
For example, the default policy correlates to: |
| 399 |
|
| 400 |
.. code-block:: python |
| 401 |
|
| 402 |
add.apply_async((2, 2), retry=True, retry_policy={ |
| 403 |
'max_retries': 3, |
| 404 |
'interval_start': 0, |
| 405 |
'interval_step': 0.2, |
| 406 |
'interval_max': 0.2, |
| 407 |
'retry_errors': None, |
| 408 |
}) |
| 409 |
|
| 410 |
the maximum time spent retrying will be 0.4 seconds. It's set relatively |
| 411 |
short by default because a connection failure could lead to a retry pile effect |
| 412 |
if the broker connection is down -- For example, many web server processes waiting |
| 413 |
to retry, blocking other incoming requests. |
| 414 |
|
| 415 |
.. _calling-connection-errors: |
| 416 |
|
| 417 |
Connection Error Handling |
| 418 |
========================= |
| 419 |
|
| 420 |
When you send a task and the message transport connection is lost, or |
| 421 |
the connection cannot be initiated, an :exc:`~kombu.exceptions.OperationalError` |
| 422 |
error will be raised: |
| 423 |
|
| 424 |
.. code-block:: pycon |
| 425 |
|
| 426 |
>>> from proj.tasks import add |
| 427 |
>>> add.delay(2, 2) |
| 428 |
Traceback (most recent call last): |
| 429 |
File "<stdin>", line 1, in <module> |
| 430 |
File "celery/app/task.py", line 388, in delay |
| 431 |
return self.apply_async(args, kwargs) |
| 432 |
File "celery/app/task.py", line 503, in apply_async |
| 433 |
**options |
| 434 |
File "celery/app/base.py", line 662, in send_task |
| 435 |
amqp.send_task_message(P, name, message, **options) |
| 436 |
File "celery/backends/rpc.py", line 275, in on_task_call |
| 437 |
maybe_declare(self.binding(producer.channel), retry=True) |
| 438 |
File "/opt/celery/kombu/kombu/messaging.py", line 204, in _get_channel |
| 439 |
channel = self._channel = channel() |
| 440 |
File "/opt/celery/py-amqp/amqp/connection.py", line 272, in connect |
| 441 |
self.transport.connect() |
| 442 |
File "/opt/celery/py-amqp/amqp/transport.py", line 100, in connect |
| 443 |
self._connect(self.host, self.port, self.connect_timeout) |
| 444 |
File "/opt/celery/py-amqp/amqp/transport.py", line 141, in _connect |
| 445 |
self.sock.connect(sa) |
| 446 |
kombu.exceptions.OperationalError: [Errno 61] Connection refused |
| 447 |
|
| 448 |
If you have :ref:`retries <calling-retry>` enabled this will only happen after |
| 449 |
retries are exhausted, or when disabled immediately. |
| 450 |
|
| 451 |
You can handle this error too: |
| 452 |
|
| 453 |
.. code-block:: pycon |
| 454 |
|
| 455 |
>>> from celery.utils.log import get_logger |
| 456 |
>>> logger = get_logger(__name__) |
| 457 |
|
| 458 |
>>> try: |
| 459 |
... add.delay(2, 2) |
| 460 |
... except add.OperationalError as exc: |
| 461 |
... logger.exception('Sending task raised: %r', exc) |
| 462 |
|
| 463 |
.. note:: |
| 464 |
|
| 465 |
With RabbitMQ, these errors only indicate the broker is unreachable. |
| 466 |
Messages can still be silently dropped when the broker hits resource |
| 467 |
limits. Enable ``confirm_publish`` in :setting:`broker_transport_options` |
| 468 |
to detect this. |
| 469 |
|
| 470 |
.. _calling-serializers: |
| 471 |
|
| 472 |
Serializers |
| 473 |
=========== |
| 474 |
|
| 475 |
.. sidebar:: Security |
| 476 |
|
| 477 |
The pickle module allows for execution of arbitrary functions, |
| 478 |
please see the :ref:`security guide <guide-security>`. |
| 479 |
|
| 480 |
Celery also comes with a special serializer that uses |
| 481 |
cryptography to sign your messages. |
| 482 |
|
| 483 |
Data transferred between clients and workers needs to be serialized, |
| 484 |
so every message in Celery has a ``content_type`` header that |
| 485 |
describes the serialization method used to encode it. |
| 486 |
|
| 487 |
The default serializer is `JSON`, but you can |
| 488 |
change this using the :setting:`task_serializer` setting, |
| 489 |
or for each individual task, or even per message. |
| 490 |
|
| 491 |
There's built-in support for `JSON`, :mod:`pickle`, `YAML` |
| 492 |
and ``msgpack``, and you can also add your own custom serializers by registering |
| 493 |
them into the Kombu serializer registry |
| 494 |
|
| 495 |
.. seealso:: |
| 496 |
|
| 497 |
:ref:`Message Serialization <kombu:guide-serialization>` in the Kombu user |
| 498 |
guide. |
| 499 |
|
| 500 |
Each option has its advantages and disadvantages. |
| 501 |
|
| 502 |
json -- JSON is supported in many programming languages, is now |
| 503 |
a standard part of Python (since 2.6), and is fairly fast to decode. |
| 504 |
|
| 505 |
The primary disadvantage to JSON is that it limits you to the following |
| 506 |
data types: strings, Unicode, floats, Boolean, dictionaries, and lists. |
| 507 |
Decimals and dates are notably missing. |
| 508 |
|
| 509 |
Binary data will be transferred using Base64 encoding, |
| 510 |
increasing the size of the transferred data by 34% compared to an encoding |
| 511 |
format where native binary types are supported. |
| 512 |
|
| 513 |
However, if your data fits inside the above constraints and you need |
| 514 |
cross-language support, the default setting of JSON is probably your |
| 515 |
best choice. |
| 516 |
|
| 517 |
See http://json.org for more information. |
| 518 |
|
| 519 |
.. note:: |
| 520 |
|
| 521 |
(From Python official docs https://docs.python.org/3.6/library/json.html) |
| 522 |
Keys in key/value pairs of JSON are always of the type :class:`str`. When |
| 523 |
a dictionary is converted into JSON, all the keys of the dictionary are |
| 524 |
coerced to strings. As a result of this, if a dictionary is converted |
| 525 |
into JSON and then back into a dictionary, the dictionary may not equal |
| 526 |
the original one. That is, ``loads(dumps(x)) != x`` if x has non-string |
| 527 |
keys. |
| 528 |
|
| 529 |
.. warning:: |
| 530 |
|
| 531 |
With more complex workflows created using :ref:`guide-canvas`, the JSON |
| 532 |
serializer has been observed to drastically inflate message sizes due to |
| 533 |
recursive references, leading to resource issues. The *pickle* serializer |
| 534 |
is not vulnerable to this and may therefore be preferable in such cases. |
| 535 |
|
| 536 |
pickle -- If you have no desire to support any language other than |
| 537 |
Python, then using the pickle encoding will gain you the support of |
| 538 |
all built-in Python data types (except class instances), smaller |
| 539 |
messages when sending binary files, and a slight speedup over JSON |
| 540 |
processing. |
| 541 |
|
| 542 |
See :mod:`pickle` for more information. |
| 543 |
|
| 544 |
yaml -- YAML has many of the same characteristics as json, |
| 545 |
except that it natively supports more data types (including dates, |
| 546 |
recursive references, etc.). |
| 547 |
|
| 548 |
However, the Python libraries for YAML are a good bit slower than the |
| 549 |
libraries for JSON. |
| 550 |
|
| 551 |
If you need a more expressive set of data types and need to maintain |
| 552 |
cross-language compatibility, then YAML may be a better fit than the above. |
| 553 |
|
| 554 |
To use it, install Celery with: |
| 555 |
|
| 556 |
.. code-block:: console |
| 557 |
|
| 558 |
$ pip install celery[yaml] |
| 559 |
|
| 560 |
See http://yaml.org/ for more information. |
| 561 |
|
| 562 |
msgpack -- msgpack is a binary serialization format that's closer to JSON |
| 563 |
in features. The format compresses better, so is a faster to parse and |
| 564 |
encode compared to JSON. |
| 565 |
|
| 566 |
To use it, install Celery with: |
| 567 |
|
| 568 |
.. code-block:: console |
| 569 |
|
| 570 |
$ pip install celery[msgpack] |
| 571 |
|
| 572 |
See http://msgpack.org/ for more information. |
| 573 |
|
| 574 |
To use a custom serializer you need to add the content type to |
| 575 |
:setting:`accept_content`. By default, only JSON is accepted, |
| 576 |
and tasks containing other content headers are rejected. |
| 577 |
|
| 578 |
The following order is used to decide the serializer |
| 579 |
used when sending a task: |
| 580 |
|
| 581 |
1. The `serializer` execution option. |
| 582 |
2. The :attr:`@-Task.serializer` attribute |
| 583 |
3. The :setting:`task_serializer` setting. |
| 584 |
|
| 585 |
|
| 586 |
Example setting a custom serializer for a single task invocation: |
| 587 |
|
| 588 |
.. code-block:: pycon |
| 589 |
|
| 590 |
>>> add.apply_async((10, 10), serializer='json') |
| 591 |
|
| 592 |
.. _calling-compression: |
| 593 |
|
| 594 |
Compression |
| 595 |
=========== |
| 596 |
|
| 597 |
Celery can compress messages using the following builtin schemes: |
| 598 |
|
| 599 |
- `brotli` |
| 600 |
|
| 601 |
brotli is optimized for the web, in particular small text |
| 602 |
documents. It is most effective for serving static content |
| 603 |
such as fonts and html pages. |
| 604 |
|
| 605 |
To use it, install Celery with: |
| 606 |
|
| 607 |
.. code-block:: console |
| 608 |
|
| 609 |
$ pip install celery[brotli] |
| 610 |
|
| 611 |
- `bzip2` |
| 612 |
|
| 613 |
bzip2 creates smaller files than gzip, but compression and |
| 614 |
decompression speeds are noticeably slower than those of gzip. |
| 615 |
|
| 616 |
To use it, please ensure your Python executable was compiled |
| 617 |
with bzip2 support. |
| 618 |
|
| 619 |
If you get the following :class:`ImportError`: |
| 620 |
|
| 621 |
.. code-block:: pycon |
| 622 |
|
| 623 |
>>> import bz2 |
| 624 |
Traceback (most recent call last): |
| 625 |
File "<stdin>", line 1, in <module> |
| 626 |
ImportError: No module named 'bz2' |
| 627 |
|
| 628 |
it means that you should recompile your Python version with bzip2 support. |
| 629 |
|
| 630 |
- `gzip` |
| 631 |
|
| 632 |
gzip is suitable for systems that require a small memory footprint, |
| 633 |
making it ideal for systems with limited memory. It is often |
| 634 |
used to generate files with the ".tar.gz" extension. |
| 635 |
|
| 636 |
To use it, please ensure your Python executable was compiled |
| 637 |
with gzip support. |
| 638 |
|
| 639 |
If you get the following :class:`ImportError`: |
| 640 |
|
| 641 |
.. code-block:: pycon |
| 642 |
|
| 643 |
>>> import gzip |
| 644 |
Traceback (most recent call last): |
| 645 |
File "<stdin>", line 1, in <module> |
| 646 |
ImportError: No module named 'gzip' |
| 647 |
|
| 648 |
it means that you should recompile your Python version with gzip support. |
| 649 |
|
| 650 |
- `lzma` |
| 651 |
|
| 652 |
lzma provides a good compression ratio and executes with |
| 653 |
fast compression and decompression speeds at the expense |
| 654 |
of higher memory usage. |
| 655 |
|
| 656 |
To use it, please ensure your Python executable was compiled |
| 657 |
with lzma support and that your Python version is 3.3 and above. |
| 658 |
|
| 659 |
If you get the following :class:`ImportError`: |
| 660 |
|
| 661 |
.. code-block:: pycon |
| 662 |
|
| 663 |
>>> import lzma |
| 664 |
Traceback (most recent call last): |
| 665 |
File "<stdin>", line 1, in <module> |
| 666 |
ImportError: No module named 'lzma' |
| 667 |
|
| 668 |
it means that you should recompile your Python version with lzma support. |
| 669 |
|
| 670 |
Alternatively, you can also install a backport using: |
| 671 |
|
| 672 |
.. code-block:: console |
| 673 |
|
| 674 |
$ pip install celery[lzma] |
| 675 |
|
| 676 |
- `zlib` |
| 677 |
|
| 678 |
zlib is an abstraction of the Deflate algorithm in library |
| 679 |
form which includes support both for the gzip file format |
| 680 |
and a lightweight stream format in its API. It is a crucial |
| 681 |
component of many software systems - Linux kernel and Git VCS just |
| 682 |
to name a few. |
| 683 |
|
| 684 |
To use it, please ensure your Python executable was compiled |
| 685 |
with zlib support. |
| 686 |
|
| 687 |
If you get the following :class:`ImportError`: |
| 688 |
|
| 689 |
.. code-block:: pycon |
| 690 |
|
| 691 |
>>> import zlib |
| 692 |
Traceback (most recent call last): |
| 693 |
File "<stdin>", line 1, in <module> |
| 694 |
ImportError: No module named 'zlib' |
| 695 |
|
| 696 |
it means that you should recompile your Python version with zlib support. |
| 697 |
|
| 698 |
- `zstd` |
| 699 |
|
| 700 |
zstd targets real-time compression scenarios at zlib-level |
| 701 |
and better compression ratios. It's backed by a very fast entropy |
| 702 |
stage, provided by Huff0 and FSE library. |
| 703 |
|
| 704 |
To use it, install Celery with: |
| 705 |
|
| 706 |
.. code-block:: console |
| 707 |
|
| 708 |
$ pip install celery[zstd] |
| 709 |
|
| 710 |
You can also create your own compression schemes and register |
| 711 |
them in the :func:`kombu compression registry <kombu.compression.register>`. |
| 712 |
|
| 713 |
The following order is used to decide the compression scheme |
| 714 |
used when sending a task: |
| 715 |
|
| 716 |
1. The `compression` execution option. |
| 717 |
2. The :attr:`@-Task.compression` attribute. |
| 718 |
3. The :setting:`task_compression` attribute. |
| 719 |
|
| 720 |
Example specifying the compression used when calling a task:: |
| 721 |
|
| 722 |
>>> add.apply_async((2, 2), compression='zlib') |
| 723 |
|
| 724 |
.. _calling-connections: |
| 725 |
|
| 726 |
Connections |
| 727 |
=========== |
| 728 |
|
| 729 |
.. sidebar:: Automatic Pool Support |
| 730 |
|
| 731 |
Since version 2.3 there's support for automatic connection pools, |
| 732 |
so you don't have to manually handle connections and publishers |
| 733 |
to reuse connections. |
| 734 |
|
| 735 |
The connection pool is enabled by default since version 2.5. |
| 736 |
|
| 737 |
See the :setting:`broker_pool_limit` setting for more information. |
| 738 |
|
| 739 |
You can handle the connection manually by creating a |
| 740 |
publisher: |
| 741 |
|
| 742 |
.. code-block:: python |
| 743 |
|
| 744 |
numbers = [(2, 2), (4, 4), (8, 8), (16, 16)] |
| 745 |
results = [] |
| 746 |
with add.app.pool.acquire(block=True) as connection: |
| 747 |
with add.get_publisher(connection) as publisher: |
| 748 |
try: |
| 749 |
for i, j in numbers: |
| 750 |
res = add.apply_async((i, j), publisher=publisher) |
| 751 |
results.append(res) |
| 752 |
print([res.get() for res in results]) |
| 753 |
|
| 754 |
|
| 755 |
Though this particular example is much better expressed as a group: |
| 756 |
|
| 757 |
.. code-block:: pycon |
| 758 |
|
| 759 |
>>> from celery import group |
| 760 |
|
| 761 |
>>> numbers = [(2, 2), (4, 4), (8, 8), (16, 16)] |
| 762 |
>>> res = group(add.s(i, j) for i, j in numbers).apply_async() |
| 763 |
|
| 764 |
>>> res.get() |
| 765 |
[4, 8, 16, 32] |
| 766 |
|
| 767 |
.. _calling-routing: |
| 768 |
|
| 769 |
Routing options |
| 770 |
=============== |
| 771 |
|
| 772 |
Celery can route tasks to different queues. |
| 773 |
|
| 774 |
Simple routing (name <-> name) is accomplished using the ``queue`` option:: |
| 775 |
|
| 776 |
add.apply_async(queue='priority.high') |
| 777 |
|
| 778 |
You can then assign workers to the ``priority.high`` queue by using |
| 779 |
the workers :option:`-Q <celery worker -Q>` argument: |
| 780 |
|
| 781 |
.. code-block:: console |
| 782 |
|
| 783 |
$ celery -A proj worker -l INFO -Q celery,priority.high |
| 784 |
|
| 785 |
.. seealso:: |
| 786 |
|
| 787 |
Hard-coding queue names in code isn't recommended, the best practice |
| 788 |
is to use configuration routers (:setting:`task_routes`). |
| 789 |
|
| 790 |
To find out more about routing, please see :ref:`guide-routing`. |
| 791 |
|
| 792 |
.. _calling-results: |
| 793 |
|
| 794 |
Results options |
| 795 |
=============== |
| 796 |
|
| 797 |
You can enable or disable result storage using the :setting:`task_ignore_result` |
| 798 |
setting or by using the ``ignore_result`` option: |
| 799 |
|
| 800 |
.. code-block:: pycon |
| 801 |
|
| 802 |
>>> result = add.apply_async((1, 2), ignore_result=True) |
| 803 |
>>> result.get() |
| 804 |
None |
| 805 |
|
| 806 |
>>> # Do not ignore result (default) |
| 807 |
... |
| 808 |
>>> result = add.apply_async((1, 2), ignore_result=False) |
| 809 |
>>> result.get() |
| 810 |
3 |
| 811 |
|
| 812 |
If you'd like to store additional metadata about the task in the result backend |
| 813 |
set the :setting:`result_extended` setting to ``True``. |
| 814 |
|
| 815 |
.. note:: |
| 816 |
|
| 817 |
``result_extended`` controls what *Celery* includes as extended task metadata, |
| 818 |
but it does not automatically add scheduler-specific metadata. |
| 819 |
For example, some integrations (e.g. :pypi:`django-celery-beat` together with |
| 820 |
:pypi:`django-celery-results`) may record the *periodic task name* in the result |
| 821 |
backend only when the scheduler provides it as part of the published message. |
| 822 |
|
| 823 |
When you call tasks manually using ``apply_async``/``delay``, that periodic task |
| 824 |
context is usually not present unless you add it explicitly (e.g. via message |
| 825 |
headers/properties in ``apply_async`` options). For example: |
| 826 |
|
| 827 |
.. code-block:: python |
| 828 |
|
| 829 |
result = task.apply_async( |
| 830 |
headers={"periodic_task_name": "task_name"}, |
| 831 |
) |
| 832 |
|
| 833 |
.. seealso:: |
| 834 |
|
| 835 |
For more information on tasks, please see :ref:`guide-tasks`. |
| 836 |
|
| 837 |
Advanced Options |
| 838 |
---------------- |
| 839 |
|
| 840 |
These options are for advanced users who want to take use of |
| 841 |
AMQP's full routing capabilities. Interested parties may read the |
| 842 |
:ref:`routing guide <guide-routing>`. |
| 843 |
|
| 844 |
- exchange |
| 845 |
|
| 846 |
Name of exchange (or a :class:`kombu.entity.Exchange`) to |
| 847 |
send the message to. |
| 848 |
|
| 849 |
- routing_key |
| 850 |
|
| 851 |
Routing key used to determine. |
| 852 |
|
| 853 |
- priority |
| 854 |
|
| 855 |
A number between `0` and `255`, where `255` is the highest priority. |
| 856 |
|
| 857 |
Supported by: RabbitMQ, Redis (priority reversed, 0 is highest). |