first-steps-with-celery.rst 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. .. _tut-celery:
  2. ========================
  3. First steps with Celery
  4. ========================
  5. .. contents::
  6. :local:
  7. .. _celerytut-simple-tasks:
  8. Creating a simple task
  9. ======================
  10. In this tutorial we are creating a simple task that adds two
  11. numbers. Tasks are defined in normal Python modules.
  12. By convention we will call our moudule :file:`tasks.py`, and it looks
  13. **:file:`tasks.py`:**
  14. .. code-block:: python
  15. from celery.decorators import task
  16. @task
  17. def add(x, y):
  18. return x + y
  19. All Celery tasks are classes that inherits from the
  20. :class:`~clery.task.base.Task` class. In this example we're using a
  21. decorator that wraps the add function in an appropriate class for us
  22. automatically.
  23. .. seealso::
  24. The full documentation on how to create tasks and task classes is in the
  25. :doc:`../userguide/tasks` part of the user guide.
  26. .. _celerytut-conf:
  27. Configuration
  28. =============
  29. Celery is configured by using a configuration module. By default
  30. this module is called :file:`celeryconfig.py`.
  31. The configuration module must either be in the current directory
  32. or on the Python path, so that it can be imported.
  33. You can also set a custom name for the configuration module by using
  34. the :envvar:`CELERY_CONFIG_MODULE` environment variable.
  35. Let's create our :file:`celeryconfig.py`.
  36. 1. Configure how we communicate with the broker (RabbitMQ in this example)::
  37. BROKER_HOST = "localhost"
  38. BROKER_PORT = 5672
  39. BROKER_USER = "myuser"
  40. BROKER_PASSWORD = "mypassword"
  41. BROKER_VHOST = "myvhost"
  42. 2. Define the backend used to store task metadata and return values::
  43. CELERY_RESULT_BACKEND = "amqp"
  44. The AMQP backend is non-persistent by default, and you can only
  45. fetch the result of a task once (as it's sent as a message).
  46. For list of backends available and related options see
  47. :ref:`conf-result-backend`.
  48. 3. Finally we list the modules the worker should import. This includes
  49. the modules containing your tasks.
  50. We only have a single task module, :file:`tasks.py`, which we added earlier::
  51. CELERY_IMPORTS = ("tasks", )
  52. That's it.
  53. There are more options available, like how many processes you want to
  54. use to process work in parallel (the :setting:`CELERY_CONCURRENCY` setting),
  55. and we could use a persistent result store backend, but for now, this should
  56. do. For all of the options available, see :ref:`configuration`.
  57. .. note::
  58. You can also specify modules to import using the :option:`-I` option to
  59. :mod:`~celery.bin.celeryd`::
  60. $ celeryd -l info -I tasks,handlers
  61. This can be a single, or a comma separated list of task modules to import
  62. when :program:`celeryd` starts.
  63. .. _celerytut-running-celeryd:
  64. Running the celery worker server
  65. ================================
  66. To test we will run the worker server in the foreground, so we can
  67. see what's going on in the terminal::
  68. $ celeryd --loglevel=INFO
  69. In production you will probably want to run the worker in the
  70. background as a daemon. To do this you need to use the tools provided
  71. by your platform, or something like `supervisord`_ (see :ref:`daemonization`
  72. for more information).
  73. For a complete listing of the command line options available, do::
  74. $ celeryd --help
  75. .. _`supervisord`: http://supervisord.org
  76. .. _celerytut-executing-task:
  77. Executing the task
  78. ==================
  79. Whenever we want to execute our task, we use the
  80. :meth:`~celery.task.base.Task.delay` method of the task class.
  81. This is a handy shortcut to the :meth:`~celery.task.base.Task.apply_async`
  82. method which gives greater control of the task execution (see
  83. :ref:`guide-executing`).
  84. >>> from tasks import add
  85. >>> add.delay(4, 4)
  86. <AsyncResult: 889143a6-39a2-4e52-837b-d80d33efb22d>
  87. At this point, the task has been sent to the message broker. The message
  88. broker will hold on to the task until a worker server has consumed and
  89. executed it.
  90. Right now we have to check the worker log files to know what happened
  91. with the task. This is because we didn't keep the
  92. :class:`~celery.result.AsyncResult` object returned.
  93. The :class:`~celery.result.AsyncResult` lets us check the state of the task,
  94. wait for the task to finish, get its return value or exception/traceback
  95. if the task failed, and more.
  96. Let's execute the task again -- but this time we'll keep track of the task
  97. by holding on to the :class:`~celery.result.AsyncResult`::
  98. >>> result = add.delay(4, 4)
  99. >>> result.ready() # returns True if the task has finished processing.
  100. False
  101. >>> result.result # task is not ready, so no return value yet.
  102. None
  103. >>> result.get() # Waits until the task is done and returns the retval.
  104. 8
  105. >>> result.result # direct access to result, doesn't re-raise errors.
  106. 8
  107. >>> result.successful() # returns True if the task didn't end in failure.
  108. True
  109. If the task raises an exception, the return value of ``result.successful()``
  110. will be :const:`False`, and ``result.result`` will contain the exception instance
  111. raised by the task.
  112. Where to go from here
  113. =====================
  114. After this you should read the :ref:`guide`. Specifically
  115. :ref:`guide-tasks` and :ref:`guide-executing`.