calling.rst 15 KB

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