celery.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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, force=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. :keyword force: Force reading configuration immediately.
  100. By default the configuration will be read only when required.
  101. .. code-block:: python
  102. >>> celery.config_from_object("myapp.celeryconfig")
  103. >>> from myapp import celeryconfig
  104. >>> celery.config_from_object(celeryconfig)
  105. .. method:: Celery.config_from_envvar(variable_name,
  106. silent=False, force=False)
  107. Read configuration from environment variable.
  108. The value of the environment variable must be the name
  109. of a module to import.
  110. .. code-block:: python
  111. >>> os.environ["CELERY_CONFIG_MODULE"] = "myapp.celeryconfig"
  112. >>> celery.config_from_envvar("CELERY_CONFIG_MODULE")
  113. .. method:: Celery.autodiscover_tasks(packages, related_name="tasks")
  114. With a list of packages, try to import modules of a specific name (by
  115. default 'tasks').
  116. For example if you have an (imagined) directory tree like this::
  117. foo/__init__.py
  118. tasks.py
  119. models.py
  120. bar/__init__.py
  121. tasks.py
  122. models.py
  123. baz/__init__.py
  124. models.py
  125. Then calling ``app.autodiscover_tasks(['foo', bar', 'baz'])`` will
  126. result in the modules ``foo.tasks`` and ``bar.tasks`` being imported.
  127. :param packages: List of packages to search.
  128. This argument may also be a callable, in which case the
  129. value returned is used (for lazy evaluation).
  130. :keyword related_name: The name of the module to find. Defaults
  131. to "tasks", which means it look for "module.tasks" for every
  132. module in ``packages``.
  133. :keyword force: By default this call is lazy so that the actual
  134. autodiscovery will not happen until an application imports the
  135. default modules. Forcing will cause the autodiscovery to happen
  136. immediately.
  137. .. method:: Celery.add_defaults(d)
  138. Add default configuration from dict ``d``.
  139. If the argument is a callable function then it will be regarded
  140. as a promise, and it won't be loaded until the configuration is
  141. actually needed.
  142. This method can be compared to::
  143. >>> celery.conf.update(d)
  144. with a difference that 1) no copy will be made and 2) the dict will
  145. not be transferred when the worker spawns child processes, so
  146. it's important that the same configuration happens at import time
  147. when pickle restores the object on the other side.
  148. .. method:: Celery.setup_security(…)
  149. Setup the message-signing serializer.
  150. This will affect all application instances (a global operation).
  151. Disables untrusted serializers and if configured to use the ``auth``
  152. serializer will register the auth serializer with the provided settings
  153. into the Kombu serializer registry.
  154. :keyword allowed_serializers: List of serializer names, or content_types
  155. that should be exempt from being disabled.
  156. :keyword key: Name of private key file to use.
  157. Defaults to the :setting:`CELERY_SECURITY_KEY` setting.
  158. :keyword cert: Name of certificate file to use.
  159. Defaults to the :setting:`CELERY_SECURITY_CERTIFICATE` setting.
  160. :keyword store: Directory containing certificates.
  161. Defaults to the :setting:`CELERY_SECURITY_CERT_STORE` setting.
  162. :keyword digest: Digest algorithm used when signing messages.
  163. Default is ``sha1``.
  164. :keyword serializer: Serializer used to encode messages after
  165. they have been signed. See :setting:`CELERY_TASK_SERIALIZER` for
  166. the serializers supported.
  167. Default is ``json``.
  168. .. method:: Celery.start(argv=None)
  169. Run :program:`celery` using `argv`.
  170. Uses :data:`sys.argv` if `argv` is not specified.
  171. .. method:: Celery.task(fun, …)
  172. Decorator to create a task class out of any callable.
  173. Examples:
  174. .. code-block:: python
  175. @app.task
  176. def refresh_feed(url):
  177. return …
  178. with setting extra options:
  179. .. code-block:: python
  180. @app.task(exchange="feeds")
  181. def refresh_feed(url):
  182. return …
  183. .. admonition:: App Binding
  184. For custom apps the task decorator will return a proxy
  185. object, so that the act of creating the task is not performed
  186. until the task is used or the task registry is accessed.
  187. If you are depending on binding to be deferred, then you must
  188. not access any attributes on the returned object until the
  189. application is fully set up (finalized).
  190. .. method:: Celery.send_task(name[, args[, kwargs[, …]]])
  191. Send task by name.
  192. :param name: Name of task to call (e.g. `"tasks.add"`).
  193. :keyword result_cls: Specify custom result class. Default is
  194. using :meth:`AsyncResult`.
  195. Otherwise supports the same arguments as :meth:`@-Task.apply_async`.
  196. .. attribute:: Celery.AsyncResult
  197. Create new result instance. See :class:`~celery.result.AsyncResult`.
  198. .. attribute:: Celery.GroupResult
  199. Create new group result instance.
  200. See :class:`~celery.result.GroupResult`.
  201. .. method:: Celery.worker_main(argv=None)
  202. Run :program:`celery worker` using `argv`.
  203. Uses :data:`sys.argv` if `argv` is not specified.
  204. .. attribute:: Celery.Worker
  205. Worker application. See :class:`~@Worker`.
  206. .. attribute:: Celery.WorkController
  207. Embeddable worker. See :class:`~@WorkController`.
  208. .. attribute:: Celery.Beat
  209. Celerybeat scheduler application.
  210. See :class:`~@Beat`.
  211. .. method:: Celery.connection(url=default, [ssl, [transport_options={}]])
  212. Establish a connection to the message broker.
  213. :param url: Either the URL or the hostname of the broker to use.
  214. :keyword hostname: URL, Hostname/IP-address of the broker.
  215. If an URL is used, then the other argument below will
  216. be taken from the URL instead.
  217. :keyword userid: Username to authenticate as.
  218. :keyword password: Password to authenticate with
  219. :keyword virtual_host: Virtual host to use (domain).
  220. :keyword port: Port to connect to.
  221. :keyword ssl: Defaults to the :setting:`BROKER_USE_SSL` setting.
  222. :keyword transport: defaults to the :setting:`BROKER_TRANSPORT`
  223. setting.
  224. :returns :class:`kombu.Connection`:
  225. .. method:: Celery.connection_or_acquire(connection=None)
  226. For use within a with-statement to get a connection from the pool
  227. if one is not already provided.
  228. :keyword connection: If not provided, then a connection will be
  229. acquired from the connection pool.
  230. .. method:: Celery.producer_or_acquire(producer=None)
  231. For use within a with-statement to get a producer from the pool
  232. if one is not already provided
  233. :keyword producer: If not provided, then a producer will be
  234. acquired from the producer pool.
  235. .. method:: Celery.mail_admins(subject, body, fail_silently=False)
  236. Sends an email to the admins in the :setting:`ADMINS` setting.
  237. .. method:: Celery.select_queues(queues=[])
  238. Select a subset of queues, where queues must be a list of queue
  239. names to keep.
  240. .. method:: Celery.now()
  241. Return the current time and date as a :class:`~datetime.datetime`
  242. object.
  243. .. method:: Celery.set_current()
  244. Makes this the current app for this thread.
  245. .. method:: Celery.finalize()
  246. Finalizes the app by loading built-in tasks,
  247. and evaluating pending task decorators
  248. .. attribute:: Celery.Pickler
  249. Helper class used to pickle this application.
  250. Canvas primitives
  251. -----------------
  252. See :ref:`guide-canvas` for more about creating task workflows.
  253. .. class:: group(task1[, task2[, task3[,… taskN]]])
  254. Creates a group of tasks to be executed in parallel.
  255. Example::
  256. >>> res = group([add.s(2, 2), add.s(4, 4)])()
  257. >>> res.get()
  258. [4, 8]
  259. A group is lazy so you must call it to take action and evaluate
  260. the group.
  261. Will return a `group` task that when called will then call of the
  262. tasks in the group (and return a :class:`GroupResult` instance
  263. that can be used to inspect the state of the group).
  264. .. class:: chain(task1[, task2[, task3[,… taskN]]])
  265. Chains tasks together, so that each tasks follows each other
  266. by being applied as a callback of the previous task.
  267. If called with only one argument, then that argument must
  268. be an iterable of tasks to chain.
  269. Example::
  270. >>> res = chain(add.s(2, 2), add.s(4))()
  271. is effectively :math:`(2 + 2) + 4)`::
  272. >>> res.get()
  273. 8
  274. Calling a chain will return the result of the last task in the chain.
  275. You can get to the other tasks by following the ``result.parent``'s::
  276. >>> res.parent.get()
  277. 4
  278. .. class:: chord(header[, body])
  279. A chord consists of a header and a body.
  280. The header is a group of tasks that must complete before the callback is
  281. called. A chord is essentially a callback for a group of tasks.
  282. Example::
  283. >>> res = chord([add.s(2, 2), add.s(4, 4)])(sum_task.s())
  284. is effectively :math:`\Sigma ((2 + 2) + (4 + 4))`::
  285. >>> res.get()
  286. 12
  287. The body is applied with the return values of all the header
  288. tasks as a list.
  289. .. class:: signature(task=None, args=(), kwargs={}, options={})
  290. Describes the arguments and execution options for a single task invocation.
  291. Used as the parts in a :class:`group` or to safely pass
  292. tasks around as callbacks.
  293. Signatures can also be created from tasks::
  294. >>> add.subtask(args=(), kwargs={}, options={})
  295. or the ``.s()`` shortcut::
  296. >>> add.s(*args, **kwargs)
  297. :param task: Either a task class/instance, or the name of a task.
  298. :keyword args: Positional arguments to apply.
  299. :keyword kwargs: Keyword arguments to apply.
  300. :keyword options: Additional options to :meth:`Task.apply_async`.
  301. Note that if the first argument is a :class:`dict`, the other
  302. arguments will be ignored and the values in the dict will be used
  303. instead.
  304. >>> s = signature("tasks.add", args=(2, 2))
  305. >>> signature(s)
  306. {"task": "tasks.add", args=(2, 2), kwargs={}, options={}}
  307. .. method:: signature.__call__(*args \*\*kwargs)
  308. Call the task directly (in the current process).
  309. .. method:: signature.delay(*args, \*\*kwargs)
  310. Shortcut to :meth:`apply_async`.
  311. .. method:: signature.apply_async(args=(), kwargs={}, …)
  312. Apply this task asynchronously.
  313. :keyword args: Partial args to be prepended to the existing args.
  314. :keyword kwargs: Partial kwargs to be merged with the existing kwargs.
  315. :keyword options: Partial options to be merged with the existing
  316. options.
  317. See :meth:`~@Task.apply_async`.
  318. .. method:: signature.apply(args=(), kwargs={}, …)
  319. Same as :meth:`apply_async` but executed the task inline instead
  320. of sending a task message.
  321. .. method:: signature.freeze(_id=None)
  322. Finalize the signature by adding a concrete task id.
  323. The task will not be called and you should not call the signature
  324. twice after freezing it as that will result in two task messages
  325. using the same task id.
  326. :returns: :class:`@AsyncResult` instance.
  327. .. method:: signature.clone(args=(), kwargs={}, …)
  328. Return a copy of this signature.
  329. :keyword args: Partial args to be prepended to the existing args.
  330. :keyword kwargs: Partial kwargs to be merged with the existing kwargs.
  331. :keyword options: Partial options to be merged with the existing
  332. options.
  333. .. method:: signature.replace(args=None, kwargs=None, options=None)
  334. Replace the args, kwargs or options set for this signature.
  335. These are only replaced if the selected is not :const:`None`.
  336. .. method:: signature.link(other_signature)
  337. Add a callback task to be applied if this task
  338. executes successfully.
  339. :returns: ``other_signature`` (to work with :func:`~functools.reduce`).
  340. .. method:: signature.link_error(other_signature)
  341. Add a callback task to be applied if an error occurs
  342. while executing this task.
  343. :returns: ``other_signature`` (to work with :func:`~functools.reduce`)
  344. .. method:: signature.set(…)
  345. Set arbitrary options (same as ``.options.update(…)``).
  346. This is a chaining method call (i.e. it will return ``self``).
  347. .. method:: signature.flatten_links()
  348. Gives a recursive list of dependencies (unchain if you will,
  349. but with links intact).
  350. Proxies
  351. -------
  352. .. data:: current_app
  353. The currently set app for this thread.
  354. .. data:: current_task
  355. The task currently being executed
  356. (only set in the worker, or when eager/apply is used).