Debian Codegraph @

docs/getting-started/first-steps-with-celery.rst

raw
1 .. _tut-celery:
2 .. _first-steps:
3
4 =========================
5 First Steps with Celery
6 =========================
7
8 Celery is a task queue with batteries included.
9 It's easy to use so that you can get started without learning
10 the full complexities of the problem it solves. It's designed
11 around best practices so that your product can scale
12 and integrate with other languages, and it comes with the
13 tools and support you need to run such a system in production.
14
15 In this tutorial you'll learn the absolute basics of using Celery.
16
17 Learn about:
18
19 - Choosing and installing a message transport (broker).
20 - Installing Celery and creating your first task.
21 - Starting the worker and calling tasks.
22 - Keeping track of tasks as they transition through different states,
23 and inspecting return values.
24
25 Celery may seem daunting at first - but don't worry - this tutorial
26 will get you started in no time. It's deliberately kept simple, so
27 as to not confuse you with advanced features.
28 After you have finished this tutorial,
29 it's a good idea to browse the rest of the documentation.
30 For example the :ref:`next-steps` tutorial will
31 showcase Celery's capabilities.
32
33 .. contents::
34 :local:
35
36 .. _celerytut-broker:
37
38 Choosing a Broker
39 =================
40
41 Celery requires a solution to send and receive messages; usually this
42 comes in the form of a separate service called a *message broker*.
43
44 There are several choices available, including:
45
46 RabbitMQ
47 --------
48
49 `RabbitMQ`_ is feature-complete, stable, durable and easy to install.
50 It's an excellent choice for a production environment.
51 Detailed information about using RabbitMQ with Celery:
52
53 :ref:`broker-rabbitmq`
54
55 .. _`RabbitMQ`: http://www.rabbitmq.com/
56
57 If you're using Ubuntu or Debian install RabbitMQ by executing this
58 command:
59
60 .. code-block:: console
61
62 $ sudo apt-get install rabbitmq-server
63
64 Or, if you want to run it on Docker execute this:
65
66 .. code-block:: console
67
68 $ docker run -d -p 5672:5672 rabbitmq
69
70 When the command completes, the broker will already be running in the background,
71 ready to move messages for you: ``Starting rabbitmq-server: SUCCESS``.
72
73 Don't worry if you're not running Ubuntu or Debian, you can go to this
74 website to find similarly simple installation instructions for other
75 platforms, including Microsoft Windows:
76
77 http://www.rabbitmq.com/download.html
78
79 Redis
80 -----
81
82 `Redis`_ is also feature-complete, but is more susceptible to data loss in
83 the event of abrupt termination or power failures. Detailed information about using Redis:
84
85 :ref:`broker-redis`
86
87 .. _`Redis`: https://redis.io/
88
89 If you want to run it on Docker execute this:
90
91 .. code-block:: console
92
93 $ docker run -d -p 6379:6379 redis
94
95 Other brokers
96 -------------
97
98 In addition to the above, there are other experimental transport implementations
99 to choose from, including :ref:`Amazon SQS <broker-sqs>`.
100
101 See :ref:`broker-overview` for a full list.
102
103 .. _celerytut-installation:
104
105 Installing Celery
106 =================
107
108 Celery is on the Python Package Index (PyPI), so it can be installed
109 with standard Python tools like ``pip``:
110
111 .. code-block:: console
112
113 $ pip install celery
114
115 Application
116 ===========
117
118 The first thing you need is a Celery instance. We call this the *Celery
119 application* or just *app* for short. As this instance is used as
120 the entry-point for everything you want to do in Celery, like creating tasks and
121 managing workers, it must be possible for other modules to import it.
122
123 In this tutorial we keep everything contained in a single module,
124 but for larger projects you want to create
125 a :ref:`dedicated module <project-layout>`.
126
127 Let's create the file :file:`tasks.py`:
128
129 .. code-block:: python
130
131 from celery import Celery
132
133 app = Celery('tasks', broker='pyamqp://guest@localhost//')
134
135 @app.task
136 def add(x, y):
137 return x + y
138
139 The first argument to :class:`~celery.app.Celery` is the name of the current module.
140 This is only needed so that names can be automatically generated when the tasks are
141 defined in the `__main__` module.
142
143 The second argument is the broker keyword argument, specifying the URL of the
144 message broker you want to use. Here we are using RabbitMQ (also the default option).
145
146 See :ref:`celerytut-broker` above for more choices --
147 for RabbitMQ you can use ``amqp://localhost``, or for Redis you can
148 use ``redis://localhost``.
149
150 You defined a single task, called ``add``, returning the sum of two numbers.
151
152 .. _celerytut-running-the-worker:
153
154 Running the Celery worker server
155 ================================
156
157 You can now run the worker by executing our program with the ``worker``
158 argument:
159
160 .. code-block:: console
161
162 $ celery -A tasks worker --loglevel=INFO
163
164 .. note::
165
166 See the :ref:`celerytut-troubleshooting` section if the worker
167 doesn't start.
168
169 In production you'll want to run the worker in the
170 background as a daemon. To do this you need to use the tools provided
171 by your platform, or something like `supervisord`_ (see :ref:`daemonizing`
172 for more information).
173
174 For a complete listing of the command-line options available, do:
175
176 .. code-block:: console
177
178 $ celery worker --help
179
180 There are also several other commands available, and help is also available:
181
182 .. code-block:: console
183
184 $ celery --help
185
186 .. _`supervisord`: http://supervisord.org
187
188 .. _celerytut-calling:
189
190 Calling the task
191 ================
192
193 To call our task you can use the :meth:`[email protected]` method.
194
195 This is a handy shortcut to the :meth:`[email protected]_async`
196 method that gives greater control of the task execution (see
197 :ref:`guide-calling`)::
198
199 >>> from tasks import add
200 >>> add.delay(4, 4)
201
202 The task has now been processed by the worker you started earlier.
203 You can verify this by looking at the worker's console output.
204
205 Calling a task returns an :class:`~@AsyncResult` instance.
206 This can be used to check the state of the task, wait for the task to finish,
207 or get its return value (or if the task failed, to get the exception and traceback).
208
209 Results are not enabled by default. In order to do remote procedure calls
210 or keep track of task results in a database, you will need to configure Celery to use a result
211 backend. This is described in the next section.
212
213 .. _celerytut-keeping-results:
214
215 Keeping Results
216 ===============
217
218 If you want to keep track of the tasks' states, Celery needs to store or send
219 the states somewhere. There are several
220 built-in result backends to choose from: `SQLAlchemy`_/`Django`_ ORM,
221 `MongoDB`_, `Memcached`_, `Redis`_, :ref:`RPC <conf-rpc-result-backend>` (`RabbitMQ`_/AMQP),
222 and -- or you can define your own.
223
224 .. _`Memcached`: http://memcached.org
225 .. _`MongoDB`: http://www.mongodb.org
226 .. _`SQLAlchemy`: http://www.sqlalchemy.org/
227 .. _`Django`: http://djangoproject.com
228
229 For this example we use the `rpc` result backend, that sends states
230 back as transient messages. The backend is specified via the ``backend`` argument to
231 :class:`@Celery`, (or via the :setting:`result_backend` setting if
232 you choose to use a configuration module). So, you can modify this line in the `tasks.py`
233 file to enable the `rpc://` backend:
234
235 .. code-block:: python
236
237 app = Celery('tasks', backend='rpc://', broker='pyamqp://')
238
239 Or if you want to use Redis as the result backend, but still use RabbitMQ as
240 the message broker (a popular combination):
241
242 .. code-block:: python
243
244 app = Celery('tasks', backend='redis://localhost', broker='pyamqp://')
245
246 To read more about result backends please see :ref:`task-result-backends`.
247
248 Now with the result backend configured, restart the worker, close the current python session and import the
249 ``tasks`` module again to put the changes into effect. This time you'll hold on to the
250 :class:`~@AsyncResult` instance returned when you call a task:
251
252 .. code-block:: pycon
253
254 >>> from tasks import add # close and reopen to get updated 'app'
255 >>> result = add.delay(4, 4)
256
257 The :meth:`[email protected]` method returns whether the task
258 has finished processing or not:
259
260 .. code-block:: pycon
261
262 >>> result.ready()
263 False
264
265 You can wait for the result to complete, but this is rarely used
266 since it turns the asynchronous call into a synchronous one:
267
268 .. code-block:: pycon
269
270 >>> result.get(timeout=1)
271 8
272
273 In case the task raised an exception, :meth:`[email protected]` will
274 re-raise the exception, but you can override this by specifying
275 the ``propagate`` argument:
276
277 .. code-block:: pycon
278
279 >>> result.get(propagate=False)
280
281
282 If the task raised an exception, you can also gain access to the
283 original traceback:
284
285 .. code-block:: pycon
286
287 >>> result.traceback
288
289 .. warning::
290
291 Backends use resources to store and transmit results. To ensure
292 that resources are released, you must eventually call
293 :meth:`[email protected]` or :meth:`[email protected]` on
294 EVERY :class:`~@AsyncResult` instance returned after calling
295 a task.
296
297 See :mod:`celery.result` for the complete result object reference.
298
299 .. _celerytut-configuration:
300
301 Configuration
302 =============
303
304 Celery, like a consumer appliance, doesn't need much configuration to operate.
305 It has an input and an output. The input must be connected to a broker, and the output can
306 be optionally connected to a result backend. However, if you look closely at the back,
307 there's a lid revealing loads of sliders, dials, and buttons: this is the configuration.
308
309 The default configuration should be good enough for most use cases, but there are
310 many options that can be configured to make Celery work exactly as needed.
311 Reading about the options available is a good idea to familiarize yourself with what
312 can be configured. You can read about the options in the
313 :ref:`configuration` reference.
314
315 The configuration can be set on the app directly or by using a dedicated
316 configuration module.
317 As an example you can configure the default serializer used for serializing
318 task payloads by changing the :setting:`task_serializer` setting:
319
320 .. code-block:: python
321
322 app.conf.task_serializer = 'json'
323
324 If you're configuring many settings at once you can use ``update``:
325
326 .. code-block:: python
327
328 app.conf.update(
329 task_serializer='json',
330 accept_content=['json'], # Ignore other content
331 result_serializer='json',
332 timezone='Europe/Oslo',
333 enable_utc=True,
334 )
335
336 For larger projects, a dedicated configuration module is recommended.
337 Hard coding periodic task intervals and task routing options is discouraged.
338 It is much better to keep these in a centralized location. This is especially
339 true for libraries, as it enables users to control how their tasks behave.
340 A centralized configuration will also allow your SysAdmin to make simple changes
341 in the event of system trouble.
342
343 You can tell your Celery instance to use a configuration module
344 by calling the :meth:`@config_from_object` method:
345
346 .. code-block:: python
347
348 app.config_from_object('celeryconfig')
349
350 This module is often called "``celeryconfig``", but you can use any
351 module name.
352
353 In the above case, a module named ``celeryconfig.py`` must be available to load from the
354 current directory or on the Python path. It could look something like this:
355
356 :file:`celeryconfig.py`:
357
358 .. code-block:: python
359
360 broker_url = 'pyamqp://'
361 result_backend = 'rpc://'
362
363 task_serializer = 'json'
364 result_serializer = 'json'
365 accept_content = ['json']
366 timezone = 'Europe/Oslo'
367 enable_utc = True
368
369 To verify that your configuration file works properly and doesn't
370 contain any syntax errors, you can try to import it:
371
372 .. code-block:: console
373
374 $ python -m celeryconfig
375
376 For a complete reference of configuration options, see :ref:`configuration`.
377
378 To demonstrate the power of configuration files, this is how you'd
379 route a misbehaving task to a dedicated queue:
380
381 :file:`celeryconfig.py`:
382
383 .. code-block:: python
384
385 task_routes = {
386 'tasks.add': 'low-priority',
387 }
388
389 Or instead of routing it you could rate limit the task
390 instead, so that only 10 tasks of this type can be processed in a minute
391 (10/m):
392
393 :file:`celeryconfig.py`:
394
395 .. code-block:: python
396
397 task_annotations = {
398 'tasks.add': {'rate_limit': '10/m'}
399 }
400
401 If you're using RabbitMQ or Redis as the
402 broker then you can also direct the workers to set a new rate limit
403 for the task at runtime:
404
405 .. code-block:: console
406
407 $ celery -A tasks control rate_limit tasks.add 10/m
408 [email protected]: OK
409 new rate limit set successfully
410
411 See :ref:`guide-routing` to read more about task routing,
412 and the :setting:`task_annotations` setting for more about annotations,
413 or :ref:`guide-monitoring` for more about remote control commands
414 and how to monitor what your workers are doing.
415
416 Where to go from here
417 =====================
418
419 If you want to learn more you should continue to the
420 :ref:`Next Steps <next-steps>` tutorial, and after that you
421 can read the :ref:`User Guide <guide>`.
422
423 .. _celerytut-troubleshooting:
424
425 Troubleshooting
426 ===============
427
428 There's also a troubleshooting section in the :ref:`faq`.
429
430 Worker doesn't start: Permission Error
431 --------------------------------------
432
433 - If you're using Debian, Ubuntu or other Debian-based distributions:
434
435 Debian recently renamed the :file:`/dev/shm` special file
436 to :file:`/run/shm`.
437
438 A simple workaround is to create a symbolic link:
439
440 .. code-block:: console
441
442 # ln -s /run/shm /dev/shm
443
444 - Others:
445
446 If you provide any of the :option:`--pidfile <celery worker --pidfile>`,
447 :option:`--logfile <celery worker --logfile>` or
448 :option:`--statedb <celery worker --statedb>` arguments, then you must
449 make sure that they point to a file or directory that's writable and
450 readable by the user starting the worker.
451
452 Result backend doesn't work or tasks are always in ``PENDING`` state
453 --------------------------------------------------------------------
454
455 All tasks are :state:`PENDING` by default, so the state would've been
456 better named "unknown". Celery doesn't update the state when a task
457 is sent, and any task with no history is assumed to be pending (you know
458 the task id, after all).
459
460 1) Make sure that the task doesn't have ``ignore_result`` enabled.
461
462 Enabling this option will force the worker to skip updating
463 states.
464
465 2) Make sure the :setting:`task_ignore_result` setting isn't enabled.
466
467 3) Make sure that you don't have any old workers still running.
468
469 It's easy to start multiple workers by accident, so make sure
470 that the previous worker is properly shut down before you start a new one.
471
472 An old worker that isn't configured with the expected result backend
473 may be running and is hijacking the tasks.
474
475 The :option:`--pidfile <celery worker --pidfile>` argument can be set to
476 an absolute path to make sure this doesn't happen.
477
478 4) Make sure the client is configured with the right backend.
479
480 If, for some reason, the client is configured to use a different backend
481 than the worker, you won't be able to receive the result.
482 Make sure the backend is configured correctly:
483
484 .. code-block:: pycon
485
486 >>> result = task.delay()
487 >>> print(result.backend)