calling.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. .. _guide-calling:
  2. ===============
  3. Calling Tasks
  4. ===============
  5. .. contents::
  6. :local:
  7. :depth: 1
  8. .. _calling-basics:
  9. Basics
  10. ======
  11. This document describes Celery's uniform "Calling API"
  12. used by task instances and the :ref:`canvas <guide-canvas>`.
  13. The API defines a standard set of execution options, as well as three methods:
  14. - ``apply_async(args[, kwargs[, …]])``
  15. Sends a task message.
  16. - ``delay(*args, **kwargs)``
  17. Shortcut to send a task message, but does not support execution
  18. options.
  19. - *calling* (``__call__``)
  20. Applying an object supporting the calling API (e.g. ``add(2, 2)``)
  21. means that the task will be executed in the current process, and
  22. not by a worker (a message will not be sent).
  23. .. _calling-cheat:
  24. .. topic:: Quick Cheat Sheet
  25. - ``T.delay(arg, kwarg=value)``
  26. always a shortcut to ``.apply_async``.
  27. - ``T.apply_async((arg, ), {'kwarg': value})``
  28. - ``T.apply_async(countdown=10)``
  29. executes 10 seconds from now.
  30. - ``T.apply_async(eta=now + timedelta(seconds=10))``
  31. executes 10 seconds from now, specifed using ``eta``
  32. - ``T.apply_async(countdown=60, expires=120)``
  33. executes in one minute from now, but expires after 2 minutes.
  34. - ``T.apply_async(expires=now + timedelta(days=2))``
  35. expires in 2 days, set using :class:`~datetime.datetime`.
  36. Example
  37. -------
  38. The :meth:`~@Task.delay` method is convenient as it looks like calling a regular
  39. function:
  40. .. code-block:: python
  41. task.delay(arg1, arg2, kwarg1='x', kwarg2='y')
  42. Using :meth:`~@Task.apply_async` instead you have to write:
  43. .. code-block:: python
  44. task.apply_async(args=[arg1, arg2], kwargs={'kwarg1': 'x', 'kwarg2': 'y'})
  45. .. sidebar:: Tip
  46. If the task is not registered in the current process
  47. you can use :meth:`~@send_task` to call the task by name instead.
  48. So `delay` is clearly convenient, but if you want to set additional execution
  49. options you have to use ``apply_async``.
  50. The rest of this document will go into the task execution
  51. options in detail. All examples use a task
  52. called `add`, returning the sum of two arguments:
  53. .. code-block:: python
  54. @app.task
  55. def add(x, y):
  56. return x + y
  57. .. topic:: There's another way…
  58. You will learn more about this later while reading about the :ref:`Canvas
  59. <guide-canvas>`, but :class:`~celery.subtask`'s are objects used to pass around
  60. the signature of a task invocation, (for example to send it over the
  61. network), and they also support the Calling API:
  62. .. code-block:: python
  63. task.s(arg1, arg2, kwarg1='x', kwargs2='y').apply_async()
  64. .. _calling-links:
  65. Linking (callbacks/errbacks)
  66. ============================
  67. Celery supports linking tasks together so that one task follows another.
  68. The callback task will be applied with the result of the parent task
  69. as a partial argument:
  70. .. code-block:: python
  71. add.apply_async((2, 2), link=add.s(16))
  72. .. sidebar:: What is ``s``?
  73. The ``add.s`` call used here is called a subtask, I talk
  74. more about subtasks in the :ref:`canvas guide <guide-canvas>`,
  75. where you can also learn about :class:`~celery.chain`, which
  76. is a simpler way to chain tasks together.
  77. In practice the ``link`` execution option is considered an internal
  78. primitive, and you will probably not use it directly, but
  79. rather use chains instead.
  80. Here the result of the first task (4) will be sent to a new
  81. task that adds 16 to the previous result, forming the expression
  82. :math:`(2 + 2) + 16 = 20`
  83. You can also cause a callback to be applied if task raises an exception
  84. (*errback*), but this behaves differently from a regular callback
  85. in that it will be passed the id of the parent task, not the result.
  86. This is because it may not always be possible to serialize
  87. the exception raised, and so this way the error callback requires
  88. a result backend to be enabled, and the task must retrieve the result
  89. of the task instead.
  90. This is an example error callback:
  91. .. code-block:: python
  92. @app.task
  93. def error_handler(uuid):
  94. result = AsyncResult(uuid)
  95. exc = result.get(propagate=False)
  96. print('Task {0} raised exception: {1!r}\n{2!r}'.format(
  97. uuid, exc, result.traceback))
  98. it can be added to the task using the ``link_error`` execution
  99. option:
  100. .. code-block:: python
  101. add.apply_async((2, 2), link_error=error_handler.s())
  102. In addition, both the ``link`` and ``link_error`` options can be expressed
  103. as a list::
  104. add.apply_async((2, 2), link=[add.s(16), other_task.s()])
  105. The callbacks/errbacks will then be called in order, and all
  106. callbacks will be called with the return value of the parent task
  107. as a partial argument.
  108. .. _calling-eta:
  109. ETA and countdown
  110. =================
  111. The ETA (estimated time of arrival) lets you set a specific date and time that
  112. is the earliest time at which your task will be executed. `countdown` is
  113. a shortcut to set eta by seconds into the future.
  114. .. code-block:: python
  115. >>> result = add.apply_async((2, 2), countdown=3)
  116. >>> result.get() # this takes at least 3 seconds to return
  117. 20
  118. The task is guaranteed to be executed at some time *after* the
  119. specified date and time, but not necessarily at that exact time.
  120. Possible reasons for broken deadlines may include many items waiting
  121. in the queue, or heavy network latency. To make sure your tasks
  122. are executed in a timely manner you should monitor the queue for congestion. Use
  123. Munin, or similar tools, to receive alerts, so appropriate action can be
  124. taken to ease the workload. See :ref:`monitoring-munin`.
  125. While `countdown` is an integer, `eta` must be a :class:`~datetime.datetime`
  126. object, specifying an exact date and time (including millisecond precision,
  127. and timezone information):
  128. .. code-block:: python
  129. >>> from datetime import datetime, timedelta
  130. >>> tomorrow = datetime.utcnow() + timedelta(days=1)
  131. >>> add.apply_async((2, 2), eta=tomorrow)
  132. .. _calling-expiration:
  133. Expiration
  134. ==========
  135. The `expires` argument defines an optional expiry time,
  136. either as seconds after task publish, or a specific date and time using
  137. :class:`~datetime.datetime`:
  138. .. code-block:: python
  139. >>> # Task expires after one minute from now.
  140. >>> add.apply_async((10, 10), expires=60)
  141. >>> # Also supports datetime
  142. >>> from datetime import datetime, timedelta
  143. >>> add.apply_async((10, 10), kwargs,
  144. ... expires=datetime.now() + timedelta(days=1)
  145. When a worker receives an expired task it will mark
  146. the task as :state:`REVOKED` (:exc:`~@TaskRevokedError`).
  147. .. _calling-retry:
  148. Message Sending Retry
  149. =====================
  150. Celery will automatically retry sending messages in the event of connection
  151. failure, and retry behavior can be configured -- like how often to retry, or a maximum
  152. number of retries -- or disabled all together.
  153. To disable retry you can set the ``retry`` execution option to :const:`False`:
  154. .. code-block:: python
  155. add.apply_async((2, 2), retry=False)
  156. .. topic:: Related Settings
  157. .. hlist::
  158. :columns: 2
  159. - :setting:`CELERY_TASK_PUBLISH_RETRY`
  160. - :setting:`CELERY_TASK_PUBLISH_RETRY_POLICY`
  161. Retry Policy
  162. ------------
  163. A retry policy is a mapping that controls how retries behave,
  164. and can contain the following keys:
  165. - `max_retries`
  166. Maximum number of retries before giving up, in this case the
  167. exception that caused the retry to fail will be raised.
  168. A value of 0 or :const:`None` means it will retry forever.
  169. The default is to retry 3 times.
  170. - `interval_start`
  171. Defines the number of seconds (float or integer) to wait between
  172. retries. Default is 0, which means the first retry will be
  173. instantaneous.
  174. - `interval_step`
  175. On each consecutive retry this number will be added to the retry
  176. delay (float or integer). Default is 0.2.
  177. - `interval_max`
  178. Maximum number of seconds (float or integer) to wait between
  179. retries. Default is 0.2.
  180. For example, the default policy correlates to:
  181. .. code-block:: python
  182. add.apply_async((2, 2), retry=True, retry_policy={
  183. 'max_retries': 3,
  184. 'interval_start': 0,
  185. 'interval_step': 0.2,
  186. 'interval_max': 0.2,
  187. })
  188. the maximum time spent retrying will be 0.4 seconds. It is set relatively
  189. short by default because a connection failure could lead to a retry pile effect
  190. if the broker connection is down: e.g. many web server processes waiting
  191. to retry blocking other incoming requests.
  192. .. _calling-serializers:
  193. Serializers
  194. ===========
  195. .. sidebar:: Security
  196. The pickle module allows for execution of arbitrary functions,
  197. please see the :ref:`security guide <guide-security>`.
  198. Celery also comes with a special serializer that uses
  199. cryptography to sign your messages.
  200. Data transferred between clients and workers needs to be serialized,
  201. so every message in Celery has a ``content_type`` header that
  202. describes the serialization method used to encode it.
  203. The default serializer is :mod:`pickle`, but you can
  204. change this using the :setting:`CELERY_TASK_SERIALIZER` setting,
  205. or for each individual task, or even per message.
  206. There's built-in support for :mod:`pickle`, `JSON`, `YAML`
  207. and `msgpack`, and you can also add your own custom serializers by registering
  208. them into the Kombu serializer registry (see ref:`kombu:guide-serialization`).
  209. Each option has its advantages and disadvantages.
  210. json -- JSON is supported in many programming languages, is now
  211. a standard part of Python (since 2.6), and is fairly fast to decode
  212. using the modern Python libraries such as :mod:`cjson` or :mod:`simplejson`.
  213. The primary disadvantage to JSON is that it limits you to the following
  214. data types: strings, Unicode, floats, boolean, dictionaries, and lists.
  215. Decimals and dates are notably missing.
  216. Also, binary data will be transferred using Base64 encoding, which will
  217. cause the transferred data to be around 34% larger than an encoding which
  218. supports native binary types.
  219. However, if your data fits inside the above constraints and you need
  220. cross-language support, the default setting of JSON is probably your
  221. best choice.
  222. See http://json.org for more information.
  223. pickle -- If you have no desire to support any language other than
  224. Python, then using the pickle encoding will gain you the support of
  225. all built-in Python data types (except class instances), smaller
  226. messages when sending binary files, and a slight speedup over JSON
  227. processing.
  228. See http://docs.python.org/library/pickle.html for more information.
  229. yaml -- YAML has many of the same characteristics as json,
  230. except that it natively supports more data types (including dates,
  231. recursive references, etc.)
  232. However, the Python libraries for YAML are a good bit slower than the
  233. libraries for JSON.
  234. If you need a more expressive set of data types and need to maintain
  235. cross-language compatibility, then YAML may be a better fit than the above.
  236. See http://yaml.org/ for more information.
  237. msgpack -- msgpack is a binary serialization format that is closer to JSON
  238. in features. It is very young however, and support should be considered
  239. experimental at this point.
  240. See http://msgpack.org/ for more information.
  241. The encoding used is available as a message header, so the worker knows how to
  242. deserialize any task. If you use a custom serializer, this serializer must
  243. be available for the worker.
  244. The following order is used to decide which serializer
  245. to use when sending a task:
  246. 1. The `serializer` execution option.
  247. 2. The :attr:`@-Task.serializer` attribute
  248. 3. The :setting:`CELERY_TASK_SERIALIZER` setting.
  249. Example setting a custom serializer for a single task invocation:
  250. .. code-block:: python
  251. >>> add.apply_async((10, 10), serializer='json')
  252. .. _calling-compression:
  253. Compression
  254. ===========
  255. Celery can compress the messages using either *gzip*, or *bzip2*.
  256. You can also create your own compression schemes and register
  257. them in the :func:`kombu compression registry <kombu.compression.register>`.
  258. The following order is used to decide which compression scheme
  259. to use when sending a task:
  260. 1. The `compression` execution option.
  261. 2. The :attr:`@-Task.compression` attribute.
  262. 3. The :setting:`CELERY_MESSAGE_COMPRESSION` attribute.
  263. Example specifying the compression used when calling a task::
  264. >>> add.apply_async((2, 2), compression='zlib')
  265. .. _calling-connections:
  266. Connections
  267. ===========
  268. .. sidebar:: Automatic Pool Support
  269. Since version 2.3 there is support for automatic connection pools,
  270. so you don't have to manually handle connections and publishers
  271. to reuse connections.
  272. The connection pool is enabled by default since version 2.5.
  273. See the :setting:`BROKER_POOL_LIMIT` setting for more information.
  274. You can handle the connection manually by creating a
  275. publisher:
  276. .. code-block:: python
  277. results = []
  278. with add.app.pool.acquire(block=True) as connection:
  279. with add.get_publisher(connection) as publisher:
  280. try:
  281. for args in numbers:
  282. res = add.apply_async((2, 2), publisher=publisher)
  283. results.append(res)
  284. print([res.get() for res in results])
  285. Though this particular example is much better expressed as a group:
  286. .. code-block:: python
  287. >>> from celery import group
  288. >>> numbers = [(2, 2), (4, 4), (8, 8), (16, 16)]
  289. >>> res = group(add.subtask(n) for i in numbers).apply_async()
  290. >>> res.get()
  291. [4, 8, 16, 32]
  292. .. _calling-routing:
  293. Routing options
  294. ===============
  295. Celery can route tasks to different queues.
  296. Simple routing (name <-> name) is accomplished using the ``queue`` option::
  297. add.apply_async(queue='priority.high')
  298. You can then assign workers to the ``priority.high`` queue by using
  299. the workers :option:`-Q` argument:
  300. .. code-block:: bash
  301. $ celery worker -l info -Q celery,priority.high
  302. .. seealso::
  303. Hard-coding queue names in code is not recommended, the best practice
  304. is to use configuration routers (:setting:`CELERY_ROUTES`).
  305. To find out more about routing, please see :ref:`guide-routing`.
  306. Advanced Options
  307. ----------------
  308. These options are for advanced users who want to take use of
  309. AMQP's full routing capabilities. Interested parties may read the
  310. :ref:`routing guide <guide-routing>`.
  311. - exchange
  312. Name of exchange (or a :class:`kombu.entity.Exchange`) to
  313. send the message to.
  314. - routing_key
  315. Routing key used to determine.
  316. - priority
  317. A number between `0` and `9`, where `0` is the highest priority.
  318. Supported by: redis, beanstalk