celery.rst 16 KB

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