first-steps-with-celery.rst 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. ========================
  2. First steps with Celery
  3. ========================
  4. .. contents::
  5. :local:
  6. Creating a simple task
  7. ======================
  8. In this example we are creating a simple task that adds two
  9. numbers. Tasks are defined in a normal python module. The module can
  10. be named whatever you like, but the convention is to call it
  11. ``tasks.py``.
  12. Our addition task looks like this:
  13. ``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 inherit from the ``Task``
  20. class. In this case we're using a decorator that wraps the add
  21. function in an appropriate class for us automatically. The full
  22. documentation on how to create tasks and task classes are in
  23. :doc:`Executing Tasks<../userguide/tasks>`.
  24. Configuration
  25. =============
  26. Celery is configured by using a configuration module. By convention,
  27. this module is called ``celeryconfig.py``. This module must be in the
  28. Python path so it can be imported.
  29. You can set a custom name for the configuration module with the
  30. ``CELERY_CONFIG_MODULE`` variable. In these examples we use the
  31. default name.
  32. Let's create our ``celeryconfig.py``.
  33. 1. Configure how we communicate with the broker::
  34. BROKER_HOST = "localhost"
  35. BROKER_PORT = 5672
  36. BROKER_USER = "myuser"
  37. BROKER_PASSWORD = "mypassword"
  38. BROKER_VHOST = "myvhost"
  39. 2. In this example we don't want to store the results of the tasks, so
  40. we'll use the simplest backend available; the AMQP backend::
  41. CELERY_RESULT_BACKEND = "amqp"
  42. 3. Finally, we list the modules to import, that is, all the modules
  43. that contain tasks. This is so celery knows about what tasks it can
  44. be asked to perform. We only have a single task module,
  45. ``tasks.py``, which we added earlier::
  46. CELERY_IMPORTS = ("tasks", )
  47. That's it.
  48. There are more options available, like how many processes you want to
  49. process work in parallel (the ``CELERY_CONCURRENCY`` setting), and we
  50. could use a persistent result store backend, but for now, this should
  51. do. For all of the options available, see the
  52. :doc:`configuration directive reference<../configuration>`.
  53. Running the celery worker server
  54. ================================
  55. To test we will run the worker server in the foreground, so we can
  56. see what's going on in the terminal::
  57. $ PYTHONPATH="." celeryd --loglevel=INFO
  58. However, in production you probably want to run the worker in the
  59. background as a daemon. To do this you need to use to tools provided
  60. by your platform, or something like `supervisord`_.
  61. For a complete listing of the command line options available, use the
  62. help command::
  63. $ PYTHONPATH="." celeryd --help
  64. For info on how to run celery as standalone daemon, see
  65. :doc:`daemon mode reference<../cookbook/daemonizing>`
  66. .. _`supervisord`: http://supervisord.org
  67. Executing the task
  68. ==================
  69. Whenever we want to execute our task, we can use the ``delay`` method
  70. of the task class.
  71. This is a handy shortcut to the ``apply_async`` method which gives
  72. greater control of the task execution.
  73. See :doc:`Executing Tasks<../userguide/executing>` for more information.
  74. >>> from tasks import add
  75. >>> add.delay(4, 4)
  76. <AsyncResult: 889143a6-39a2-4e52-837b-d80d33efb22d>
  77. At this point, the task has been sent to the message broker. The message
  78. broker will hold on to the task until a celery worker server has successfully
  79. picked it up.
  80. *Note:* If everything is just hanging when you execute ``delay``, please check
  81. that RabbitMQ is running, and that the user/password has access to the virtual
  82. host you configured earlier.
  83. Right now we have to check the celery worker log files to know what happened
  84. with the task. This is because we didn't keep the ``AsyncResult`` object
  85. returned by ``delay``.
  86. The ``AsyncResult`` lets us find the state of the task, wait for the task to
  87. finish and get its return value (or exception if the task failed).
  88. So, let's execute the task again, but this time we'll keep track of the task:
  89. >>> result = add.delay(4, 4)
  90. >>> result.ready() # returns True if the task has finished processing.
  91. False
  92. >>> result.result # task is not ready, so no return value yet.
  93. None
  94. >>> result.get() # Waits until the task is done and returns the retval.
  95. 8
  96. >>> result.result # direct access to result, doesn't re-raise errors.
  97. 8
  98. >>> result.successful() # returns True if the task didn't end in failure.
  99. True
  100. If the task raises an exception, the return value of ``result.successful()``
  101. will be ``False``, and ``result.result`` will contain the exception instance
  102. raised by the task.
  103. That's all for now! After this you should probably read the :doc:`User
  104. Guide<../userguide/index>`.