first-steps-with-only-celery.rst 4.9 KB

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