| 1 |
.. _next-steps: |
| 2 |
|
| 3 |
============ |
| 4 |
Next Steps |
| 5 |
============ |
| 6 |
|
| 7 |
The :ref:`first-steps` guide is intentionally minimal. In this guide |
| 8 |
I'll demonstrate what Celery offers in more detail, including |
| 9 |
how to add Celery support for your application and library. |
| 10 |
|
| 11 |
This document doesn't document all of Celery's features and |
| 12 |
best practices, so it's recommended that you also read the |
| 13 |
:ref:`User Guide <guide>` |
| 14 |
|
| 15 |
.. contents:: |
| 16 |
:local: |
| 17 |
:depth: 1 |
| 18 |
|
| 19 |
Using Celery in your Application |
| 20 |
================================ |
| 21 |
|
| 22 |
.. _project-layout: |
| 23 |
|
| 24 |
Our Project |
| 25 |
----------- |
| 26 |
|
| 27 |
Project layout:: |
| 28 |
|
| 29 |
src/ |
| 30 |
proj/__init__.py |
| 31 |
/celery.py |
| 32 |
/tasks.py |
| 33 |
|
| 34 |
:file:`proj/celery.py` |
| 35 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 36 |
|
| 37 |
.. literalinclude:: ../../examples/next-steps/proj/celery.py |
| 38 |
:language: python |
| 39 |
|
| 40 |
In this module you created our :class:`@Celery` instance (sometimes |
| 41 |
referred to as the *app*). To use Celery within your project |
| 42 |
you simply import this instance. |
| 43 |
|
| 44 |
- The ``broker`` argument specifies the URL of the broker to use. |
| 45 |
|
| 46 |
See :ref:`celerytut-broker` for more information. |
| 47 |
|
| 48 |
- The ``backend`` argument specifies the result backend to use. |
| 49 |
|
| 50 |
It's used to keep track of task state and results. |
| 51 |
While results are disabled by default I use the RPC result backend here |
| 52 |
because I demonstrate how retrieving results work later. You may want to use |
| 53 |
a different backend for your application. They all have different |
| 54 |
strengths and weaknesses. If you don't need results, it's better |
| 55 |
to disable them. Results can also be disabled for individual tasks |
| 56 |
by setting the ``@task(ignore_result=True)`` option. |
| 57 |
|
| 58 |
See :ref:`celerytut-keeping-results` for more information. |
| 59 |
|
| 60 |
- The ``include`` argument is a list of modules to import when |
| 61 |
the worker starts. You need to add our tasks module here so |
| 62 |
that the worker is able to find our tasks. |
| 63 |
|
| 64 |
:file:`proj/tasks.py` |
| 65 |
~~~~~~~~~~~~~~~~~~~~~ |
| 66 |
|
| 67 |
.. literalinclude:: ../../examples/next-steps/proj/tasks.py |
| 68 |
:language: python |
| 69 |
|
| 70 |
|
| 71 |
Starting the worker |
| 72 |
------------------- |
| 73 |
|
| 74 |
The :program:`celery` program can be used to start the worker (you need to run the worker in the directory above |
| 75 |
`proj`, according to the example project layout the directory is `src`): |
| 76 |
|
| 77 |
.. code-block:: console |
| 78 |
|
| 79 |
$ celery -A proj worker -l INFO |
| 80 |
|
| 81 |
When the worker starts you should see a banner and some messages:: |
| 82 |
|
| 83 |
--------------- [email protected] v4.0 (latentcall) |
| 84 |
--- ***** ----- |
| 85 |
-- ******* ---- [Configuration] |
| 86 |
- *** --- * --- . broker: amqp://guest@localhost:5672// |
| 87 |
- ** ---------- . app: __main__:0x1012d8590 |
| 88 |
- ** ---------- . concurrency: 8 (processes) |
| 89 |
- ** ---------- . events: OFF (enable -E to monitor this worker) |
| 90 |
- ** ---------- |
| 91 |
- *** --- * --- [Queues] |
| 92 |
-- ******* ---- . celery: exchange:celery(direct) binding:celery |
| 93 |
--- ***** ----- |
| 94 |
|
| 95 |
[2012-06-08 16:23:51,078: WARNING/MainProcess] [email protected] has started. |
| 96 |
|
| 97 |
-- The *broker* is the URL you specified in the broker argument in our ``celery`` |
| 98 |
module. You can also specify a different broker on the command-line by using |
| 99 |
the :option:`-b <celery -b>` option. |
| 100 |
|
| 101 |
-- *Concurrency* is the number of prefork worker process used |
| 102 |
to process your tasks concurrently. When all of these are busy doing work, |
| 103 |
new tasks will have to wait for one of the tasks to finish before |
| 104 |
it can be processed. |
| 105 |
|
| 106 |
The default concurrency number is the number of CPU's on that machine |
| 107 |
(including cores). You can specify a custom number using |
| 108 |
the :option:`celery worker -c` option. |
| 109 |
There's no recommended value, as the optimal number depends on a number of |
| 110 |
factors, but if your tasks are mostly I/O-bound then you can try to increase |
| 111 |
it. Experimentation has shown that adding more than twice the number |
| 112 |
of CPU's is rarely effective, and likely to degrade performance |
| 113 |
instead. |
| 114 |
|
| 115 |
Including the default prefork pool, Celery also supports using |
| 116 |
Eventlet, Gevent, and running in a single thread (see :ref:`concurrency`). |
| 117 |
|
| 118 |
-- *Events* is an option that causes Celery to send |
| 119 |
monitoring messages (events) for actions occurring in the worker. |
| 120 |
These can be used by monitor programs like ``celery events``, |
| 121 |
and Flower -- the real-time Celery monitor, which you can read about in |
| 122 |
the :ref:`Monitoring and Management guide <guide-monitoring>`. |
| 123 |
|
| 124 |
-- *Queues* is the list of queues that the worker will consume |
| 125 |
tasks from. The worker can be told to consume from several queues |
| 126 |
at once, and this is used to route messages to specific workers |
| 127 |
as a means for Quality of Service, separation of concerns, |
| 128 |
and prioritization, all described in the :ref:`Routing Guide |
| 129 |
<guide-routing>`. |
| 130 |
|
| 131 |
You can get a complete list of command-line arguments |
| 132 |
by passing in the :option:`!--help` flag: |
| 133 |
|
| 134 |
.. code-block:: console |
| 135 |
|
| 136 |
$ celery worker --help |
| 137 |
|
| 138 |
These options are described in more detailed in the :ref:`Workers Guide <guide-workers>`. |
| 139 |
|
| 140 |
Stopping the worker |
| 141 |
~~~~~~~~~~~~~~~~~~~ |
| 142 |
|
| 143 |
To stop the worker simply hit :kbd:`Control-c`. A list of signals supported |
| 144 |
by the worker is detailed in the :ref:`Workers Guide <guide-workers>`. |
| 145 |
|
| 146 |
In the background |
| 147 |
~~~~~~~~~~~~~~~~~ |
| 148 |
|
| 149 |
In production you'll want to run the worker in the background, |
| 150 |
described in detail in the :ref:`daemonization tutorial <daemonizing>`. |
| 151 |
|
| 152 |
The daemonization scripts uses the :program:`celery multi` command to |
| 153 |
start one or more workers in the background: |
| 154 |
|
| 155 |
.. code-block:: console |
| 156 |
|
| 157 |
$ celery multi start w1 -A proj -l INFO |
| 158 |
celery multi v4.0.0 (latentcall) |
| 159 |
> Starting nodes... |
| 160 |
> w1.halcyon.local: OK |
| 161 |
|
| 162 |
You can restart it too: |
| 163 |
|
| 164 |
.. code-block:: console |
| 165 |
|
| 166 |
$ celery multi restart w1 -A proj -l INFO |
| 167 |
celery multi v4.0.0 (latentcall) |
| 168 |
> Stopping nodes... |
| 169 |
> w1.halcyon.local: TERM -> 64024 |
| 170 |
> Waiting for 1 node..... |
| 171 |
> w1.halcyon.local: OK |
| 172 |
> Restarting node w1.halcyon.local: OK |
| 173 |
celery multi v4.0.0 (latentcall) |
| 174 |
> Stopping nodes... |
| 175 |
> w1.halcyon.local: TERM -> 64052 |
| 176 |
|
| 177 |
or stop it: |
| 178 |
|
| 179 |
.. code-block:: console |
| 180 |
|
| 181 |
$ celery multi stop w1 -A proj -l INFO |
| 182 |
|
| 183 |
The ``stop`` command is asynchronous so it won't wait for the |
| 184 |
worker to shutdown. You'll probably want to use the ``stopwait`` command |
| 185 |
instead, which ensures that all currently executing tasks are completed |
| 186 |
before exiting: |
| 187 |
|
| 188 |
.. code-block:: console |
| 189 |
|
| 190 |
$ celery multi stopwait w1 -A proj -l INFO |
| 191 |
|
| 192 |
.. note:: |
| 193 |
|
| 194 |
:program:`celery multi` doesn't store information about workers |
| 195 |
so you need to use the same command-line arguments when |
| 196 |
restarting. Only the same pidfile and logfile arguments must be |
| 197 |
used when stopping. |
| 198 |
|
| 199 |
By default it'll create pid and log files in the current directory. |
| 200 |
To protect against multiple workers launching on top of each other |
| 201 |
you're encouraged to put these in a dedicated directory: |
| 202 |
|
| 203 |
.. code-block:: console |
| 204 |
|
| 205 |
$ mkdir -p /var/run/celery |
| 206 |
$ mkdir -p /var/log/celery |
| 207 |
$ celery multi start w1 -A proj -l INFO --pidfile=/var/run/celery/%n.pid \ |
| 208 |
--logfile=/var/log/celery/%n%I.log |
| 209 |
|
| 210 |
With the multi command you can start multiple workers, and there's a powerful |
| 211 |
command-line syntax to specify arguments for different workers too, |
| 212 |
for example: |
| 213 |
|
| 214 |
.. code-block:: console |
| 215 |
|
| 216 |
$ celery multi start 10 -A proj -l INFO -Q:1-3 images,video -Q:4,5 data \ |
| 217 |
-Q default -L:4,5 debug |
| 218 |
|
| 219 |
For more examples see the :mod:`~celery.bin.multi` module in the API |
| 220 |
reference. |
| 221 |
|
| 222 |
.. _app-argument: |
| 223 |
|
| 224 |
About the :option:`--app <celery --app>` argument |
| 225 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 226 |
|
| 227 |
The :option:`--app <celery --app>` argument specifies the Celery app instance |
| 228 |
to use, in the form of ``module.path:attribute`` |
| 229 |
|
| 230 |
But it also supports a shortcut form. If only a package name is specified, |
| 231 |
it'll try to search for the app instance, in the following order: |
| 232 |
|
| 233 |
With :option:`--app=proj <celery --app>`: |
| 234 |
|
| 235 |
1) an attribute named ``proj.app``, or |
| 236 |
2) an attribute named ``proj.celery``, or |
| 237 |
3) any attribute in the module ``proj`` where the value is a Celery |
| 238 |
application, or |
| 239 |
|
| 240 |
If none of these are found it'll try a submodule named ``proj.celery``: |
| 241 |
|
| 242 |
4) an attribute named ``proj.celery.app``, or |
| 243 |
5) an attribute named ``proj.celery.celery``, or |
| 244 |
6) Any attribute in the module ``proj.celery`` where the value is a Celery |
| 245 |
application. |
| 246 |
|
| 247 |
This scheme mimics the practices used in the documentation -- that is, |
| 248 |
``proj:app`` for a single contained module, and ``proj.celery:app`` |
| 249 |
for larger projects. |
| 250 |
|
| 251 |
|
| 252 |
.. _calling-tasks: |
| 253 |
|
| 254 |
Calling Tasks |
| 255 |
============= |
| 256 |
|
| 257 |
You can call a task using the :meth:`delay` method: |
| 258 |
|
| 259 |
.. code-block:: pycon |
| 260 |
|
| 261 |
>>> from proj.tasks import add |
| 262 |
|
| 263 |
>>> add.delay(2, 2) |
| 264 |
|
| 265 |
This method is actually a star-argument shortcut to another method called |
| 266 |
:meth:`apply_async`: |
| 267 |
|
| 268 |
.. code-block:: pycon |
| 269 |
|
| 270 |
>>> add.apply_async((2, 2)) |
| 271 |
|
| 272 |
The latter enables you to specify execution options like the time to run |
| 273 |
(countdown), the queue it should be sent to, and so on: |
| 274 |
|
| 275 |
.. code-block:: pycon |
| 276 |
|
| 277 |
>>> add.apply_async((2, 2), queue='lopri', countdown=10) |
| 278 |
|
| 279 |
In the above example the task will be sent to a queue named ``lopri`` and the |
| 280 |
task will execute, at the earliest, 10 seconds after the message was sent. |
| 281 |
|
| 282 |
Applying the task directly will execute the task in the current process, |
| 283 |
so that no message is sent: |
| 284 |
|
| 285 |
.. code-block:: pycon |
| 286 |
|
| 287 |
>>> add(2, 2) |
| 288 |
4 |
| 289 |
|
| 290 |
These three methods - :meth:`delay`, :meth:`apply_async`, and applying |
| 291 |
(``__call__``), make up the Celery calling API, which is also used for |
| 292 |
signatures. |
| 293 |
|
| 294 |
A more detailed overview of the Calling API can be found in the |
| 295 |
:ref:`Calling User Guide <guide-calling>`. |
| 296 |
|
| 297 |
Every task invocation will be given a unique identifier (an UUID) -- this |
| 298 |
is the task id. |
| 299 |
|
| 300 |
The ``delay`` and ``apply_async`` methods return an :class:`~@AsyncResult` |
| 301 |
instance, which can be used to keep track of the tasks execution state. |
| 302 |
But for this you need to enable a :ref:`result backend <task-result-backends>` so that |
| 303 |
the state can be stored somewhere. |
| 304 |
|
| 305 |
Results are disabled by default because there is no result |
| 306 |
backend that suits every application; to choose one you need to consider |
| 307 |
the drawbacks of each individual backend. For many tasks |
| 308 |
keeping the return value isn't even very useful, so it's a sensible default to |
| 309 |
have. Also note that result backends aren't used for monitoring tasks and workers: |
| 310 |
for that Celery uses dedicated event messages (see :ref:`guide-monitoring`). |
| 311 |
|
| 312 |
If you have a result backend configured you can retrieve the return |
| 313 |
value of a task: |
| 314 |
|
| 315 |
.. code-block:: pycon |
| 316 |
|
| 317 |
>>> res = add.delay(2, 2) |
| 318 |
>>> res.get(timeout=1) |
| 319 |
4 |
| 320 |
|
| 321 |
You can find the task's id by looking at the :attr:`id` attribute: |
| 322 |
|
| 323 |
.. code-block:: pycon |
| 324 |
|
| 325 |
>>> res.id |
| 326 |
d6b3aea2-fb9b-4ebc-8da4-848818db9114 |
| 327 |
|
| 328 |
You can also inspect the exception and traceback if the task raised an |
| 329 |
exception, in fact ``result.get()`` will propagate any errors by default: |
| 330 |
|
| 331 |
.. code-block:: pycon |
| 332 |
|
| 333 |
>>> res = add.delay(2, '2') |
| 334 |
>>> res.get(timeout=1) |
| 335 |
|
| 336 |
.. code-block:: pytb |
| 337 |
|
| 338 |
Traceback (most recent call last): |
| 339 |
File "<stdin>", line 1, in <module> |
| 340 |
File "celery/result.py", line 221, in get |
| 341 |
return self.backend.wait_for_pending( |
| 342 |
File "celery/backends/asynchronous.py", line 195, in wait_for_pending |
| 343 |
return result.maybe_throw(callback=callback, propagate=propagate) |
| 344 |
File "celery/result.py", line 333, in maybe_throw |
| 345 |
self.throw(value, self._to_remote_traceback(tb)) |
| 346 |
File "celery/result.py", line 326, in throw |
| 347 |
self.on_ready.throw(*args, **kwargs) |
| 348 |
File "vine/promises.py", line 244, in throw |
| 349 |
reraise(type(exc), exc, tb) |
| 350 |
File "vine/five.py", line 195, in reraise |
| 351 |
raise value |
| 352 |
TypeError: unsupported operand type(s) for +: 'int' and 'str' |
| 353 |
|
| 354 |
If you don't wish for the errors to propagate, you can disable that by passing ``propagate``: |
| 355 |
|
| 356 |
.. code-block:: pycon |
| 357 |
|
| 358 |
>>> res.get(propagate=False) |
| 359 |
TypeError("unsupported operand type(s) for +: 'int' and 'str'") |
| 360 |
|
| 361 |
In this case it'll return the exception instance raised instead -- |
| 362 |
so to check whether the task succeeded or failed, you'll have to |
| 363 |
use the corresponding methods on the result instance: |
| 364 |
|
| 365 |
.. code-block:: pycon |
| 366 |
|
| 367 |
>>> res.failed() |
| 368 |
True |
| 369 |
|
| 370 |
>>> res.successful() |
| 371 |
False |
| 372 |
|
| 373 |
So how does it know if the task has failed or not? It can find out by looking |
| 374 |
at the tasks *state*: |
| 375 |
|
| 376 |
.. code-block:: pycon |
| 377 |
|
| 378 |
>>> res.state |
| 379 |
'FAILURE' |
| 380 |
|
| 381 |
A task can only be in a single state, but it can progress through several |
| 382 |
states. The stages of a typical task can be:: |
| 383 |
|
| 384 |
PENDING -> STARTED -> SUCCESS |
| 385 |
|
| 386 |
The started state is a special state that's only recorded if the |
| 387 |
:setting:`task_track_started` setting is enabled, or if the |
| 388 |
``@task(track_started=True)`` option is set for the task. |
| 389 |
|
| 390 |
The pending state is actually not a recorded state, but rather |
| 391 |
the default state for any task id that's unknown: this you can see |
| 392 |
from this example: |
| 393 |
|
| 394 |
.. code-block:: pycon |
| 395 |
|
| 396 |
>>> from proj.celery import app |
| 397 |
|
| 398 |
>>> res = app.AsyncResult('this-id-does-not-exist') |
| 399 |
>>> res.state |
| 400 |
'PENDING' |
| 401 |
|
| 402 |
If the task is retried the stages can become even more complex. |
| 403 |
To demonstrate, for a task that's retried two times the stages would be: |
| 404 |
|
| 405 |
.. code-block:: text |
| 406 |
|
| 407 |
PENDING -> STARTED -> RETRY -> STARTED -> RETRY -> STARTED -> SUCCESS |
| 408 |
|
| 409 |
To read more about task states you should see the :ref:`task-states` section |
| 410 |
in the tasks user guide. |
| 411 |
|
| 412 |
Calling tasks is described in detail in the |
| 413 |
:ref:`Calling Guide <guide-calling>`. |
| 414 |
|
| 415 |
.. _designing-workflows: |
| 416 |
|
| 417 |
*Canvas*: Designing Work-flows |
| 418 |
============================== |
| 419 |
|
| 420 |
You just learned how to call a task using the tasks ``delay`` method, |
| 421 |
and this is often all you need. But sometimes you may want to pass the |
| 422 |
signature of a task invocation to another process or as an argument to another |
| 423 |
function, for which Celery uses something called *signatures*. |
| 424 |
|
| 425 |
A signature wraps the arguments and execution options of a single task |
| 426 |
invocation in such a way that it can be passed to functions or even serialized |
| 427 |
and sent across the wire. |
| 428 |
|
| 429 |
You can create a signature for the ``add`` task using the arguments ``(2, 2)``, |
| 430 |
and a countdown of 10 seconds like this: |
| 431 |
|
| 432 |
.. code-block:: pycon |
| 433 |
|
| 434 |
>>> add.signature((2, 2), countdown=10) |
| 435 |
tasks.add(2, 2) |
| 436 |
|
| 437 |
There's also a shortcut using star arguments: |
| 438 |
|
| 439 |
.. code-block:: pycon |
| 440 |
|
| 441 |
>>> add.s(2, 2) |
| 442 |
tasks.add(2, 2) |
| 443 |
|
| 444 |
And there's that calling API again… |
| 445 |
----------------------------------- |
| 446 |
|
| 447 |
Signature instances also support the calling API, meaning they |
| 448 |
have ``delay`` and ``apply_async`` methods. |
| 449 |
|
| 450 |
But there's a difference in that the signature may already have |
| 451 |
an argument signature specified. The ``add`` task takes two arguments, |
| 452 |
so a signature specifying two arguments would make a complete signature: |
| 453 |
|
| 454 |
.. code-block:: pycon |
| 455 |
|
| 456 |
>>> s1 = add.s(2, 2) |
| 457 |
>>> res = s1.delay() |
| 458 |
>>> res.get() |
| 459 |
4 |
| 460 |
|
| 461 |
But, you can also make incomplete signatures to create what we call |
| 462 |
*partials*: |
| 463 |
|
| 464 |
.. code-block:: pycon |
| 465 |
|
| 466 |
# incomplete partial: add(?, 2) |
| 467 |
>>> s2 = add.s(2) |
| 468 |
|
| 469 |
``s2`` is now a partial signature that needs another argument to be complete, |
| 470 |
and this can be resolved when calling the signature: |
| 471 |
|
| 472 |
.. code-block:: pycon |
| 473 |
|
| 474 |
# resolves the partial: add(8, 2) |
| 475 |
>>> res = s2.delay(8) |
| 476 |
>>> res.get() |
| 477 |
10 |
| 478 |
|
| 479 |
Here you added the argument 8 that was prepended to the existing argument 2 |
| 480 |
forming a complete signature of ``add(8, 2)``. |
| 481 |
|
| 482 |
Keyword arguments can also be added later; these are then merged with any |
| 483 |
existing keyword arguments, but with new arguments taking precedence: |
| 484 |
|
| 485 |
.. code-block:: pycon |
| 486 |
|
| 487 |
>>> s3 = add.s(2, 2, debug=True) |
| 488 |
>>> s3.delay(debug=False) # debug is now False. |
| 489 |
|
| 490 |
As stated, signatures support the calling API: meaning that |
| 491 |
|
| 492 |
- ``sig.apply_async(args=(), kwargs={}, **options)`` |
| 493 |
|
| 494 |
Calls the signature with optional partial arguments and partial |
| 495 |
keyword arguments. Also supports partial execution options. |
| 496 |
|
| 497 |
- ``sig.delay(*args, **kwargs)`` |
| 498 |
|
| 499 |
Star argument version of ``apply_async``. Any arguments will be prepended |
| 500 |
to the arguments in the signature, and keyword arguments is merged with any |
| 501 |
existing keys. |
| 502 |
|
| 503 |
So this all seems very useful, but what can you actually do with these? |
| 504 |
To get to that I must introduce the canvas primitives… |
| 505 |
|
| 506 |
The Primitives |
| 507 |
-------------- |
| 508 |
|
| 509 |
.. topic:: \ |
| 510 |
|
| 511 |
.. hlist:: |
| 512 |
:columns: 2 |
| 513 |
|
| 514 |
- :ref:`group <canvas-group>` |
| 515 |
- :ref:`chain <canvas-chain>` |
| 516 |
- :ref:`chord <canvas-chord>` |
| 517 |
- :ref:`map <canvas-map>` |
| 518 |
- :ref:`starmap <canvas-map>` |
| 519 |
- :ref:`chunks <canvas-chunks>` |
| 520 |
|
| 521 |
These primitives are signature objects themselves, so they can be combined |
| 522 |
in any number of ways to compose complex work-flows. |
| 523 |
|
| 524 |
.. note:: |
| 525 |
|
| 526 |
These examples retrieve results, so to try them out you need |
| 527 |
to configure a result backend. The example project |
| 528 |
above already does that (see the backend argument to :class:`~celery.Celery`). |
| 529 |
|
| 530 |
Let's look at some examples: |
| 531 |
|
| 532 |
Groups |
| 533 |
~~~~~~ |
| 534 |
|
| 535 |
A :class:`~celery.group` calls a list of tasks in parallel, |
| 536 |
and it returns a special result instance that lets you inspect the results |
| 537 |
as a group, and retrieve the return values in order. |
| 538 |
|
| 539 |
.. code-block:: pycon |
| 540 |
|
| 541 |
>>> from celery import group |
| 542 |
>>> from proj.tasks import add |
| 543 |
|
| 544 |
>>> group(add.s(i, i) for i in range(10))().get() |
| 545 |
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] |
| 546 |
|
| 547 |
- Partial group |
| 548 |
|
| 549 |
.. code-block:: pycon |
| 550 |
|
| 551 |
>>> g = group(add.s(i) for i in range(10)) |
| 552 |
>>> g(10).get() |
| 553 |
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19] |
| 554 |
|
| 555 |
Chains |
| 556 |
~~~~~~ |
| 557 |
|
| 558 |
Tasks can be linked together so that after one task returns the other |
| 559 |
is called: |
| 560 |
|
| 561 |
.. code-block:: pycon |
| 562 |
|
| 563 |
>>> from celery import chain |
| 564 |
>>> from proj.tasks import add, mul |
| 565 |
|
| 566 |
# (4 + 4) * 8 |
| 567 |
>>> chain(add.s(4, 4) | mul.s(8))().get() |
| 568 |
64 |
| 569 |
|
| 570 |
|
| 571 |
or a partial chain: |
| 572 |
|
| 573 |
.. code-block:: pycon |
| 574 |
|
| 575 |
>>> # (? + 4) * 8 |
| 576 |
>>> g = chain(add.s(4) | mul.s(8)) |
| 577 |
>>> g(4).get() |
| 578 |
64 |
| 579 |
|
| 580 |
|
| 581 |
Chains can also be written like this: |
| 582 |
|
| 583 |
.. code-block:: pycon |
| 584 |
|
| 585 |
>>> (add.s(4, 4) | mul.s(8))().get() |
| 586 |
64 |
| 587 |
|
| 588 |
Chords |
| 589 |
~~~~~~ |
| 590 |
|
| 591 |
A chord is a group with a callback: |
| 592 |
|
| 593 |
.. code-block:: pycon |
| 594 |
|
| 595 |
>>> from celery import chord |
| 596 |
>>> from proj.tasks import add, xsum |
| 597 |
|
| 598 |
>>> chord((add.s(i, i) for i in range(10)), xsum.s())().get() |
| 599 |
90 |
| 600 |
|
| 601 |
|
| 602 |
A group chained to another task will be automatically converted |
| 603 |
to a chord: |
| 604 |
|
| 605 |
.. code-block:: pycon |
| 606 |
|
| 607 |
>>> (group(add.s(i, i) for i in range(10)) | xsum.s())().get() |
| 608 |
90 |
| 609 |
|
| 610 |
|
| 611 |
Since these primitives are all of the signature type they |
| 612 |
can be combined almost however you want, for example: |
| 613 |
|
| 614 |
.. code-block:: pycon |
| 615 |
|
| 616 |
>>> upload_document.s(file) | group(apply_filter.s() for filter in filters) |
| 617 |
|
| 618 |
Be sure to read more about work-flows in the :ref:`Canvas <guide-canvas>` user |
| 619 |
guide. |
| 620 |
|
| 621 |
Routing |
| 622 |
======= |
| 623 |
|
| 624 |
Celery supports all of the routing facilities provided by AMQP, |
| 625 |
but it also supports simple routing where messages are sent to named queues. |
| 626 |
|
| 627 |
The :setting:`task_routes` setting enables you to route tasks by name |
| 628 |
and keep everything centralized in one location: |
| 629 |
|
| 630 |
.. code-block:: python |
| 631 |
|
| 632 |
app.conf.update( |
| 633 |
task_routes = { |
| 634 |
'proj.tasks.add': {'queue': 'hipri'}, |
| 635 |
}, |
| 636 |
) |
| 637 |
|
| 638 |
You can also specify the queue at runtime |
| 639 |
with the ``queue`` argument to ``apply_async``: |
| 640 |
|
| 641 |
.. code-block:: pycon |
| 642 |
|
| 643 |
>>> from proj.tasks import add |
| 644 |
>>> add.apply_async((2, 2), queue='hipri') |
| 645 |
|
| 646 |
You can then make a worker consume from this queue by |
| 647 |
specifying the :option:`celery worker -Q` option: |
| 648 |
|
| 649 |
.. code-block:: console |
| 650 |
|
| 651 |
$ celery -A proj worker -Q hipri |
| 652 |
|
| 653 |
You may specify multiple queues by using a comma-separated list. |
| 654 |
For example, you can make the worker consume from both the default |
| 655 |
queue and the ``hipri`` queue, where |
| 656 |
the default queue is named ``celery`` for historical reasons: |
| 657 |
|
| 658 |
.. code-block:: console |
| 659 |
|
| 660 |
$ celery -A proj worker -Q hipri,celery |
| 661 |
|
| 662 |
The order of the queues doesn't matter as the worker will |
| 663 |
give equal weight to the queues. |
| 664 |
|
| 665 |
To learn more about routing, including taking use of the full |
| 666 |
power of AMQP routing, see the :ref:`Routing Guide <guide-routing>`. |
| 667 |
|
| 668 |
Remote Control |
| 669 |
============== |
| 670 |
|
| 671 |
If you're using RabbitMQ (AMQP), Redis, or Qpid as the broker then |
| 672 |
you can control and inspect the worker at runtime. |
| 673 |
|
| 674 |
For example you can see what tasks the worker is currently working on: |
| 675 |
|
| 676 |
.. code-block:: console |
| 677 |
|
| 678 |
$ celery -A proj inspect active |
| 679 |
|
| 680 |
This is implemented by using broadcast messaging, so all remote |
| 681 |
control commands are received by every worker in the cluster. |
| 682 |
|
| 683 |
You can also specify one or more workers to act on the request |
| 684 |
using the :option:`--destination <celery inspect --destination>` option. |
| 685 |
This is a comma-separated list of worker host names: |
| 686 |
|
| 687 |
.. code-block:: console |
| 688 |
|
| 689 |
$ celery -A proj inspect active [email protected] |
| 690 |
|
| 691 |
If a destination isn't provided then every worker will act and reply |
| 692 |
to the request. |
| 693 |
|
| 694 |
The :program:`celery inspect` command contains commands that |
| 695 |
don't change anything in the worker; it only returns information |
| 696 |
and statistics about what's going on inside the worker. |
| 697 |
For a list of inspect commands you can execute: |
| 698 |
|
| 699 |
.. code-block:: console |
| 700 |
|
| 701 |
$ celery -A proj inspect --help |
| 702 |
|
| 703 |
Then there's the :program:`celery control` command, which contains |
| 704 |
commands that actually change things in the worker at runtime: |
| 705 |
|
| 706 |
.. code-block:: console |
| 707 |
|
| 708 |
$ celery -A proj control --help |
| 709 |
|
| 710 |
For example you can force workers to enable event messages (used |
| 711 |
for monitoring tasks and workers): |
| 712 |
|
| 713 |
.. code-block:: console |
| 714 |
|
| 715 |
$ celery -A proj control enable_events |
| 716 |
|
| 717 |
When events are enabled you can then start the event dumper |
| 718 |
to see what the workers are doing: |
| 719 |
|
| 720 |
.. code-block:: console |
| 721 |
|
| 722 |
$ celery -A proj events --dump |
| 723 |
|
| 724 |
or you can start the curses interface: |
| 725 |
|
| 726 |
.. code-block:: console |
| 727 |
|
| 728 |
$ celery -A proj events |
| 729 |
|
| 730 |
when you're finished monitoring you can disable events again: |
| 731 |
|
| 732 |
.. code-block:: console |
| 733 |
|
| 734 |
$ celery -A proj control disable_events |
| 735 |
|
| 736 |
The :program:`celery status` command also uses remote control commands |
| 737 |
and shows a list of online workers in the cluster: |
| 738 |
|
| 739 |
.. code-block:: console |
| 740 |
|
| 741 |
$ celery -A proj status |
| 742 |
|
| 743 |
You can read more about the :program:`celery` command and monitoring |
| 744 |
in the :ref:`Monitoring Guide <guide-monitoring>`. |
| 745 |
|
| 746 |
Timezone |
| 747 |
======== |
| 748 |
|
| 749 |
All times and dates, internally and in messages use the UTC timezone. |
| 750 |
|
| 751 |
When the worker receives a message, for example with a countdown set it |
| 752 |
converts that UTC time to local time. If you wish to use |
| 753 |
a different timezone than the system timezone then you must |
| 754 |
configure that using the :setting:`timezone` setting: |
| 755 |
|
| 756 |
.. code-block:: python |
| 757 |
|
| 758 |
app.conf.timezone = 'Europe/London' |
| 759 |
|
| 760 |
Optimization |
| 761 |
============ |
| 762 |
|
| 763 |
The default configuration isn't optimized for throughput. By default, |
| 764 |
it tries to walk the middle way between many short tasks and fewer long |
| 765 |
tasks, a compromise between throughput and fair scheduling. |
| 766 |
|
| 767 |
If you have strict fair scheduling requirements, or want to optimize |
| 768 |
for throughput then you should read the :ref:`Optimizing Guide |
| 769 |
<guide-optimizing>`. |
| 770 |
|
| 771 |
What to do now? |
| 772 |
=============== |
| 773 |
|
| 774 |
Now that you have read this document you should continue |
| 775 |
to the :ref:`User Guide <guide>`. |
| 776 |
|
| 777 |
There's also an :ref:`API reference <apiref>` if you're so inclined. |