celery.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. ===========================================
  2. :mod:`celery` --- Distributed processing
  3. ===========================================
  4. .. currentmodule:: celery
  5. .. module:: celery
  6. :synopsis: Distributed processing
  7. .. moduleauthor:: Ask Solem <ask@celeryproject.org>
  8. .. sectionauthor:: Ask Solem <ask@celeryproject.org>
  9. --------------
  10. This module is the main entry-point for the Celery API.
  11. It includes commonly needed things for calling tasks,
  12. and creating Celery applications.
  13. ===================== ===================================================
  14. :class:`Celery` celery application instance
  15. :class:`group` group tasks together
  16. :class:`chain` chain tasks together
  17. :class:`chord` chords enable callbacks for groups
  18. :class:`signature` object describing a task invocation
  19. :data:`current_app` proxy to the current application instance
  20. :data:`current_task` proxy to the currently executing task
  21. ===================== ===================================================
  22. :class:`Celery` application objects
  23. -----------------------------------
  24. .. versionadded:: 2.5
  25. .. class:: Celery(main='__main__', broker='amqp://localhost//', …)
  26. :param main: Name of the main module if running as `__main__`.
  27. This is used as a prefix for task names.
  28. :keyword broker: URL of the default broker used.
  29. :keyword loader: The loader class, or the name of the loader class to use.
  30. Default is :class:`celery.loaders.app.AppLoader`.
  31. :keyword backend: The result store backend class, or the name of the
  32. backend class to use. Default is the value of the
  33. :setting:`CELERY_RESULT_BACKEND` setting.
  34. :keyword amqp: AMQP object or class name.
  35. :keyword events: Events object or class name.
  36. :keyword log: Log object or class name.
  37. :keyword control: Control object or class name.
  38. :keyword set_as_current: Make this the global current app.
  39. :keyword tasks: A task registry or the name of a registry class.
  40. :keyword include: List of modules every worker should import.
  41. :keyword fixups: List of fixup plug-ins (see e.g.
  42. :mod:`celery.fixups.django`).
  43. .. attribute:: Celery.main
  44. Name of the `__main__` module. Required for standalone scripts.
  45. If set this will be used instead of `__main__` when automatically
  46. generating task names.
  47. .. attribute:: Celery.conf
  48. Current configuration.
  49. .. attribute:: user_options
  50. Custom options for command-line programs.
  51. See :ref:`extending-commandoptions`
  52. .. attribute:: steps
  53. Custom bootsteps to extend and modify the worker.
  54. See :ref:`extending-bootsteps`.
  55. .. attribute:: Celery.current_task
  56. The instance of the task that is being executed, or :const:`None`.
  57. .. attribute:: Celery.amqp
  58. AMQP related functionality: :class:`~@amqp`.
  59. .. attribute:: Celery.backend
  60. Current backend instance.
  61. .. attribute:: Celery.loader
  62. Current loader instance.
  63. .. attribute:: Celery.control
  64. Remote control: :class:`~@control`.
  65. .. attribute:: Celery.events
  66. Consuming and sending events: :class:`~@events`.
  67. .. attribute:: Celery.log
  68. Logging: :class:`~@log`.
  69. .. attribute:: Celery.tasks
  70. Task registry.
  71. Accessing this attribute will also finalize the app.
  72. .. attribute:: Celery.pool
  73. Broker connection pool: :class:`~@pool`.
  74. This attribute is not related to the workers concurrency pool.
  75. .. attribute:: Celery.Task
  76. Base task class for this app.
  77. .. attribute:: Celery.timezone
  78. Current timezone for this app.
  79. This is a cached property taking the time zone from the
  80. :setting:`CELERY_TIMEZONE` setting.
  81. .. method:: Celery.close
  82. Close any open pool connections and do any other steps necessary
  83. to clean up after the application.
  84. Only necessary for dynamically created apps for which you can
  85. use the with statement instead::
  86. with Celery(set_as_current=False) as app:
  87. with app.connection() as conn:
  88. pass
  89. .. method:: Celery.signature
  90. Return a new :class:`~celery.canvas.Signature` bound to this app.
  91. See :meth:`~celery.signature`
  92. .. method:: Celery.bugreport
  93. Return a string with information useful for the Celery core
  94. developers when reporting a bug.
  95. .. method:: Celery.config_from_object(obj, silent=False)
  96. Reads configuration from object, where object is either
  97. an object or the name of a module to import.
  98. :keyword silent: If true then import errors will be ignored.
  99. .. code-block:: python
  100. >>> celery.config_from_object("myapp.celeryconfig")
  101. >>> from myapp import celeryconfig
  102. >>> celery.config_from_object(celeryconfig)
  103. .. method:: Celery.config_from_envvar(variable_name, silent=False)
  104. Read configuration from environment variable.
  105. The value of the environment variable must be the name
  106. of a module to import.
  107. .. code-block:: python
  108. >>> os.environ["CELERY_CONFIG_MODULE"] = "myapp.celeryconfig"
  109. >>> celery.config_from_envvar("CELERY_CONFIG_MODULE")
  110. .. method:: Celery.autodiscover_tasks(packages, related_name="tasks")
  111. With a list of packages, try to import modules of a specific name (by
  112. default 'tasks').
  113. For example if you have an (imagined) directory tree like this::
  114. foo/__init__.py
  115. tasks.py
  116. models.py
  117. bar/__init__.py
  118. tasks.py
  119. models.py
  120. baz/__init__.py
  121. models.py
  122. Then calling ``app.autodiscover_tasks(['foo', bar', 'baz'])`` will
  123. result in the modules ``foo.tasks`` and ``bar.tasks`` being imported.
  124. .. method:: Celery.add_defaults(d)
  125. Add default configuration from dict ``d``.
  126. If the argument is a callable function then it will be regarded
  127. as a promise, and it won't be loaded until the configuration is
  128. actually needed.
  129. This method can be compared to::
  130. >>> celery.conf.update(d)
  131. with a difference that 1) no copy will be made and 2) the dict will
  132. not be transferred when the worker spawns child processes, so
  133. it's important that the same configuration happens at import time
  134. when pickle restores the object on the other side.
  135. .. method:: Celery.setup_security(…)
  136. Setup the message-signing serializer.
  137. This will affect all application instances (a global operation).
  138. Disables untrusted serializers and if configured to use the ``auth``
  139. serializer will register the auth serializer with the provided settings
  140. into the Kombu serializer registry.
  141. :keyword allowed_serializers: List of serializer names, or content_types
  142. that should be exempt from being disabled.
  143. :keyword key: Name of private key file to use.
  144. Defaults to the :setting:`CELERY_SECURITY_KEY` setting.
  145. :keyword cert: Name of certificate file to use.
  146. Defaults to the :setting:`CELERY_SECURITY_CERTIFICATE` setting.
  147. :keyword store: Directory containing certificates.
  148. Defaults to the :setting:`CELERY_SECURITY_CERT_STORE` setting.
  149. :keyword digest: Digest algorithm used when signing messages.
  150. Default is ``sha1``.
  151. :keyword serializer: Serializer used to encode messages after
  152. they have been signed. See :setting:`CELERY_TASK_SERIALIZER` for
  153. the serializers supported.
  154. Default is ``json``.
  155. .. method:: Celery.start(argv=None)
  156. Run :program:`celery` using `argv`.
  157. Uses :data:`sys.argv` if `argv` is not specified.
  158. .. method:: Celery.task(fun, …)
  159. Decorator to create a task class out of any callable.
  160. Examples:
  161. .. code-block:: python
  162. @celery.task
  163. def refresh_feed(url):
  164. return …
  165. with setting extra options:
  166. .. code-block:: python
  167. @celery.task(exchange="feeds")
  168. def refresh_feed(url):
  169. return …
  170. .. admonition:: App Binding
  171. For custom apps the task decorator will return a proxy
  172. object, so that the act of creating the task is not performed
  173. until the task is used or the task registry is accessed.
  174. If you are depending on binding to be deferred, then you must
  175. not access any attributes on the returned object until the
  176. application is fully set up (finalized).
  177. .. method:: Celery.send_task(name[, args[, kwargs[, …]]])
  178. Send task by name.
  179. :param name: Name of task to call (e.g. `"tasks.add"`).
  180. :keyword result_cls: Specify custom result class. Default is
  181. using :meth:`AsyncResult`.
  182. Otherwise supports the same arguments as :meth:`@-Task.apply_async`.
  183. .. attribute:: Celery.AsyncResult
  184. Create new result instance. See :class:`~celery.result.AsyncResult`.
  185. .. attribute:: Celery.GroupResult
  186. Create new group result instance.
  187. See :class:`~celery.result.GroupResult`.
  188. .. method:: Celery.worker_main(argv=None)
  189. Run :program:`celery worker` using `argv`.
  190. Uses :data:`sys.argv` if `argv` is not specified.
  191. .. attribute:: Celery.Worker
  192. Worker application. See :class:`~@Worker`.
  193. .. attribute:: Celery.WorkController
  194. Embeddable worker. See :class:`~@WorkController`.
  195. .. attribute:: Celery.Beat
  196. Celerybeat scheduler application.
  197. See :class:`~@Beat`.
  198. .. method:: Celery.connection(url=default, [ssl, [transport_options={}]])
  199. Establish a connection to the message broker.
  200. :param url: Either the URL or the hostname of the broker to use.
  201. :keyword hostname: URL, Hostname/IP-address of the broker.
  202. If an URL is used, then the other argument below will
  203. be taken from the URL instead.
  204. :keyword userid: Username to authenticate as.
  205. :keyword password: Password to authenticate with
  206. :keyword virtual_host: Virtual host to use (domain).
  207. :keyword port: Port to connect to.
  208. :keyword ssl: Defaults to the :setting:`BROKER_USE_SSL` setting.
  209. :keyword transport: defaults to the :setting:`BROKER_TRANSPORT`
  210. setting.
  211. :returns :class:`kombu.Connection`:
  212. .. method:: Celery.connection_or_acquire(connection=None)
  213. For use within a with-statement to get a connection from the pool
  214. if one is not already provided.
  215. :keyword connection: If not provided, then a connection will be
  216. acquired from the connection pool.
  217. .. method:: Celery.producer_or_acquire(producer=None)
  218. For use within a with-statement to get a producer from the pool
  219. if one is not already provided
  220. :keyword producer: If not provided, then a producer will be
  221. acquired from the producer pool.
  222. .. method:: Celery.mail_admins(subject, body, fail_silently=False)
  223. Sends an email to the admins in the :setting:`ADMINS` setting.
  224. .. method:: Celery.select_queues(queues=[])
  225. Select a subset of queues, where queues must be a list of queue
  226. names to keep.
  227. .. method:: Celery.now()
  228. Return the current time and date as a :class:`~datetime.datetime`
  229. object.
  230. .. method:: Celery.set_current()
  231. Makes this the current app for this thread.
  232. .. method:: Celery.finalize()
  233. Finalizes the app by loading built-in tasks,
  234. and evaluating pending task decorators
  235. .. attribute:: Celery.Pickler
  236. Helper class used to pickle this application.
  237. Canvas primitives
  238. -----------------
  239. See :ref:`guide-canvas` for more about creating task workflows.
  240. .. class:: group(task1[, task2[, task3[,… taskN]]])
  241. Creates a group of tasks to be executed in parallel.
  242. Example::
  243. >>> res = group([add.s(2, 2), add.s(4, 4)])()
  244. >>> res.get()
  245. [4, 8]
  246. A group is lazy so you must call it to take action and evaluate
  247. the group.
  248. Will return a `group` task that when called will then call of the
  249. tasks in the group (and return a :class:`GroupResult` instance
  250. that can be used to inspect the state of the group).
  251. .. class:: chain(task1[, task2[, task3[,… taskN]]])
  252. Chains tasks together, so that each tasks follows each other
  253. by being applied as a callback of the previous task.
  254. If called with only one argument, then that argument must
  255. be an iterable of tasks to chain.
  256. Example::
  257. >>> res = chain(add.s(2, 2), add.s(4))()
  258. is effectively :math:`(2 + 2) + 4)`::
  259. >>> res.get()
  260. 8
  261. Calling a chain will return the result of the last task in the chain.
  262. You can get to the other tasks by following the ``result.parent``'s::
  263. >>> res.parent.get()
  264. 4
  265. .. class:: chord(header[, body])
  266. A chord consists of a header and a body.
  267. The header is a group of tasks that must complete before the callback is
  268. called. A chord is essentially a callback for a group of tasks.
  269. Example::
  270. >>> res = chord([add.s(2, 2), add.s(4, 4)])(sum_task.s())
  271. is effectively :math:`\Sigma ((2 + 2) + (4 + 4))`::
  272. >>> res.get()
  273. 12
  274. The body is applied with the return values of all the header
  275. tasks as a list.
  276. .. class:: signature(task=None, args=(), kwargs={}, options={})
  277. Describes the arguments and execution options for a single task invocation.
  278. Used as the parts in a :class:`group` or to safely pass
  279. tasks around as callbacks.
  280. Signatures can also be created from tasks::
  281. >>> add.subtask(args=(), kwargs={}, options={})
  282. or the ``.s()`` shortcut::
  283. >>> add.s(*args, **kwargs)
  284. :param task: Either a task class/instance, or the name of a task.
  285. :keyword args: Positional arguments to apply.
  286. :keyword kwargs: Keyword arguments to apply.
  287. :keyword options: Additional options to :meth:`Task.apply_async`.
  288. Note that if the first argument is a :class:`dict`, the other
  289. arguments will be ignored and the values in the dict will be used
  290. instead.
  291. >>> s = signature("tasks.add", args=(2, 2))
  292. >>> signature(s)
  293. {"task": "tasks.add", args=(2, 2), kwargs={}, options={}}
  294. .. method:: signature.__call__(*args \*\*kwargs)
  295. Call the task directly (in the current process).
  296. .. method:: signature.delay(*args, \*\*kwargs)
  297. Shortcut to :meth:`apply_async`.
  298. .. method:: signature.apply_async(args=(), kwargs={}, …)
  299. Apply this task asynchronously.
  300. :keyword args: Partial args to be prepended to the existing args.
  301. :keyword kwargs: Partial kwargs to be merged with the existing kwargs.
  302. :keyword options: Partial options to be merged with the existing
  303. options.
  304. See :meth:`~@Task.apply_async`.
  305. .. method:: signature.apply(args=(), kwargs={}, …)
  306. Same as :meth:`apply_async` but executed the task inline instead
  307. of sending a task message.
  308. .. method:: signature.freeze(_id=None)
  309. Finalize the signature by adding a concrete task id.
  310. The task will not be called and you should not call the signature
  311. twice after freezing it as that will result in two task messages
  312. using the same task id.
  313. :returns: :class:`@AsyncResult` instance.
  314. .. method:: signature.clone(args=(), kwargs={}, …)
  315. Return a copy of this signature.
  316. :keyword args: Partial args to be prepended to the existing args.
  317. :keyword kwargs: Partial kwargs to be merged with the existing kwargs.
  318. :keyword options: Partial options to be merged with the existing
  319. options.
  320. .. method:: signature.replace(args=None, kwargs=None, options=None)
  321. Replace the args, kwargs or options set for this signature.
  322. These are only replaced if the selected is not :const:`None`.
  323. .. method:: signature.link(other_signature)
  324. Add a callback task to be applied if this task
  325. executes successfully.
  326. :returns: ``other_signature`` (to work with :func:`~functools.reduce`).
  327. .. method:: signature.link_error(other_signature)
  328. Add a callback task to be applied if an error occurs
  329. while executing this task.
  330. :returns: ``other_signature`` (to work with :func:`~functools.reduce`)
  331. .. method:: signature.set(…)
  332. Set arbitrary options (same as ``.options.update(…)``).
  333. This is a chaining method call (i.e. it will return ``self``).
  334. .. method:: signature.flatten_links()
  335. Gives a recursive list of dependencies (unchain if you will,
  336. but with links intact).
  337. Proxies
  338. -------
  339. .. data:: current_app
  340. The currently set app for this thread.
  341. .. data:: current_task
  342. The task currently being executed
  343. (only set in the worker, or when eager/apply is used).