celery.rst 18 KB

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