first-steps-with-celery.rst 5.5 KB

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