This document describes the current stable version of Celery (4.2). For development docs, go here.

celery — Distributed processing

This module is the main entry-point for the Celery API. It includes commonly needed things for calling tasks, and creating Celery applications.

Celery Celery application instance
group group tasks together
chain chain tasks together
chord chords enable callbacks for groups
signature() create a new task signature
Signature object describing a task invocation
current_app proxy to the current application instance
current_task proxy to the currently executing task

Celery application objects

2.5 新版功能.

class celery.Celery(main=None, loader=None, backend=None, amqp=None, events=None, log=None, control=None, set_as_current=True, tasks=None, broker=None, include=None, changes=None, config_source=None, fixups=None, task_cls=None, autofinalize=True, namespace=None, strict_typing=True, **kwargs)[源代码]

Celery application.


main (str) – Name of the main module if running as __main__. This is used as the prefix for auto-generated task names.

  • broker (str) – URL of the default broker used.
  • backend (Union[str, type]) –

    The result store backend class, or the name of the backend class to use.

    Default is the value of the result_backend setting.

  • autofinalize (bool) – If set to False a RuntimeError will be raised if the task registry or tasks are used before the app is finalized.
  • set_as_current (bool) – Make this the global current app.
  • include (List[str]) – List of modules every worker should import.
  • amqp (Union[str, type]) – AMQP object or class name.
  • events (Union[str, type]) – Events object or class name.
  • log (Union[str, type]) – Log object or class name.
  • control (Union[str, type]) – Control object or class name.
  • tasks (Union[str, type]) – A task registry, or the name of a registry class.
  • fixups (List[str]) – List of fix-up plug-ins (e.g., see celery.fixups.django).
  • config_source (Union[str, type]) – Take configuration from a class, or object. Attributes may include any settings described in the documentation.
user_options = None

Custom options for command-line programs. See Adding new command-line options

steps = None

Custom bootsteps to extend and modify the worker. See Installing Bootsteps.


Instance of task being executed, or None.


The task currently being executed by a worker or None.

Differs from current_task in that it’s not affected by tasks calling other tasks directly, or eagerly.


AMQP related functionalityamqp.


Current backend instance.


Current loader instance.


Remote controlcontrol.


Consuming and sending eventsevents.




Task registry.


Accessing this attribute will also auto-finalize the app.


Broker connection poolpool.


This attribute is not related to the workers concurrency pool.


Base task class for this app.


Current timezone for this app.

This is a cached property taking the time zone from the timezone setting.

builtin_fixups = set([u'celery.fixups.django:fixup'])

Universally unique identifier for this app.


Clean up after the application.

Only necessary for dynamically created apps, and you should probably use the with statement instead.


>>> with Celery(set_as_current=False) as app:
...     with app.connection_for_write() as conn:
...         pass
signature(*args, **kwargs)[源代码]

Return a new Signature bound to this app.


Return information useful in bug reports.

config_from_object(obj, silent=False, force=False, namespace=None)[源代码]

Read configuration from object.

Object is either an actual object or the name of a module to import.


>>> celery.config_from_object('myapp.celeryconfig')
>>> from myapp import celeryconfig
>>> celery.config_from_object(celeryconfig)
  • silent (bool) – If true then import errors will be ignored.
  • force (bool) – Force reading configuration immediately. By default the configuration will be read only when required.
config_from_envvar(variable_name, silent=False, force=False)[源代码]

Read configuration from environment variable.

The value of the environment variable must be the name of a module to import.


>>> os.environ['CELERY_CONFIG_MODULE'] = 'myapp.celeryconfig'
>>> celery.config_from_envvar('CELERY_CONFIG_MODULE')
autodiscover_tasks(packages=None, related_name=u'tasks', force=False)[源代码]

Auto-discover task modules.

Searches a list of packages for a “” module (or use related_name argument).

If the name is empty, this will be delegated to fix-ups (e.g., Django).

For example if you have a directory layout like this:




Then calling app.autodiscover_tasks(['foo', 'bar', 'baz']) will result in the modules foo.tasks and bar.tasks being imported.

  • packages (List[str]) – List of packages to search. This argument may also be a callable, in which case the value returned is used (for lazy evaluation).
  • related_name (str) – The name of the module to find. Defaults to “tasks”: meaning “look for ‘module.tasks’ for every module in packages.”
  • force (bool) – By default this call is lazy so that the actual auto-discovery won’t happen until an application imports the default modules. Forcing will cause the auto-discovery to happen immediately.

Add default configuration from dict d.

If the argument is a callable function then it will be regarded as a promise, and it won’t be loaded until the configuration is actually needed.

This method can be compared to:

>>> celery.conf.update(d)

with a difference that 1) no copy will be made and 2) the dict will not be transferred when the worker spawns child processes, so it’s important that the same configuration happens at import time when pickle restores the object on the other side.

add_periodic_task(schedule, sig, args=(), kwargs=(), name=None, **opts)[源代码]
setup_security(allowed_serializers=None, key=None, cert=None, store=None, digest=u'sha1', serializer=u'json')[源代码]

Setup the message-signing serializer.

This will affect all application instances (a global operation).

Disables untrusted serializers and if configured to use the auth serializer will register the auth serializer with the provided settings into the Kombu serializer registry.

  • allowed_serializers (Set[str]) – List of serializer names, or content_types that should be exempt from being disabled.
  • key (str) – Name of private key file to use. Defaults to the security_key setting.
  • cert (str) – Name of certificate file to use. Defaults to the security_certificate setting.
  • store (str) – Directory containing certificates. Defaults to the security_cert_store setting.
  • digest (str) – Digest algorithm used when signing messages. Default is sha1.
  • serializer (str) – Serializer used to encode messages after they’ve been signed. See task_serializer for the serializers supported. Default is json.

Run celery using argv.

Uses sys.argv if argv is not specified.

task(*args, **opts)[源代码]

Decorator to create a task class out of any callable.


def refresh_feed(url):

with setting extra options:

def refresh_feed(url):
    return store_feed(feedparser.parse(url))


App Binding: For custom apps the task decorator will return a proxy object, so that the act of creating the task is not performed until the task is used or the task registry is accessed.

If you’re depending on binding to be deferred, then you must not access any attributes on the returned object until the application is fully set up (finalized).

send_task(name, args=None, kwargs=None, countdown=None, eta=None, task_id=None, producer=None, connection=None, router=None, result_cls=None, expires=None, publisher=None, link=None, link_error=None, add_to_parent=True, group_id=None, retries=0, chord=None, reply_to=None, time_limit=None, soft_time_limit=None, root_id=None, parent_id=None, route_name=None, shadow=None, chain=None, task_type=None, **options)[源代码]

Send task by name.

Supports the same arguments as Task.apply_async().

  • name (str) – Name of task to call (e.g., “tasks.add”).
  • result_cls (AsyncResult) – Specify custom result class.
gen_task_name(name, module)[源代码]

Create new result instance.


Create new group result instance.


Run celery worker using argv.

Uses sys.argv if argv is not specified.


Worker application.




Embeddable worker.




celery beat scheduler application.



connection_for_read(url=None, **kwargs)[源代码]

Establish connection used for consuming.


connection() for supported arguments.

connection_for_write(url=None, **kwargs)[源代码]

Establish connection used for producing.


connection() for supported arguments.

connection(hostname=None, userid=None, password=None, virtual_host=None, port=None, ssl=None, connect_timeout=None, transport=None, transport_options=None, heartbeat=None, login_method=None, failover_strategy=None, **kwargs)[源代码]

Establish a connection to the message broker.

Please use connection_for_read() and connection_for_write() instead, to convey the intent of use for this connection.

  • url – Either the URL or the hostname of the broker to use.
  • hostname (str) – URL, Hostname/IP-address of the broker. If a URL is used, then the other argument below will be taken from the URL instead.
  • userid (str) – Username to authenticate as.
  • password (str) – Password to authenticate with
  • virtual_host (str) – Virtual host to use (domain).
  • port (int) – Port to connect to.
  • ssl (bool, Dict) – Defaults to the broker_use_ssl setting.
  • transport (str) – defaults to the broker_transport setting.
  • transport_options (Dict) – Dictionary of transport specific options.
  • heartbeat (int) – AMQP Heartbeat in seconds (pyamqp only).
  • login_method (str) – Custom login method to use (AMQP only).
  • failover_strategy (str, Callable) – Custom failover strategy.
  • **kwargs – Additional arguments to kombu.Connection.

the lazy connection instance.



connection_or_acquire(connection=None, pool=True, *_, **__)[源代码]

Context used to acquire a connection from the pool.

For use within a with statement to get a connection from the pool if one is not already provided.

参数:connection (kombu.Connection) – If not provided, a connection will be acquired from the connection pool.

Context used to acquire a producer from the pool.

For use within a with statement to get a producer from the pool if one is not already provided

参数:producer (kombu.Producer) – If not provided, a producer will be acquired from the producer pool.

Select subset of queues.

参数:queues (Sequence[str]) – a list of queue names to keep.

Return the current time and date as a datetime.


Make this the current app for this thread.


Make this the default app for all threads.


Finalize the app.

This loads built-in tasks, evaluates pending task decorators, reads configuration, etc.


Optional callback called at init.


Prepare configuration before it is merged with the defaults.


Signal sent when app is loading configuration.


Signal sent after app has prepared the configuration.


Signal sent after app has been finalized.


Signal sent in child process after fork.

Canvas primitives

See Canvas: Designing Work-flows for more about creating task work-flows.

class*tasks, **options)[源代码]

Creates a group of tasks to be executed in parallel.

A group is lazy so you must call it to take action and evaluate the group.


If only one argument is passed, and that argument is an iterable then that’ll be used as the list of tasks instead: this allows us to use group with generator expressions.


>>> lazy_group = group([add.s(2, 2), add.s(4, 4)])
>>> promise = lazy_group()  # <-- evaluate: returns lazy result.
>>> promise.get()  # <-- will wait for the task to return
[4, 8]
  • *tasks (List[Signature]) – A list of signatures that this group will call. If there’s only one argument, and that argument is an iterable, then that’ll define the list of signatures instead.
  • **options (Any) – Execution options applied to all tasks in the group.

signature that when called will then call all of the

tasks in the group (and return a GroupResult instance that can be used to inspect the state of the group).



class celery.chain(*tasks, **options)[源代码]

Chain tasks together.

Each tasks follows one another, by being applied as a callback of the previous task.


If called with only one argument, then that argument must be an iterable of tasks to chain: this allows us to use generator expressions.


This is effectively ((2 + 2) + 4):

>>> res = chain(add.s(2, 2), add.s(4))()
>>> res.get()

Calling a chain will return the result of the last task in the chain. You can get to the other tasks by following the result.parent’s:

>>> res.parent.get()

Using a generator expression:

>>> lazy_chain = chain(add.s(i) for i in range(10))
>>> res = lazy_chain(3)
参数:*tasks (Signature) – List of task signatures to chain. If only one argument is passed and that argument is an iterable, then that’ll be used as the list of signatures to chain instead. This means that you can use a generator expression.
A lazy signature that can be called to apply the first
task in the chain. When that task succeeed the next task in the chain is applied, and so on.
class celery.chord(header, body=None, task=u'celery.chord', args=(), kwargs={}, app=None, **options)[源代码]

Barrier synchronization primitive.

A chord consists of a header and a body.

The header is a group of tasks that must complete before the callback is called. A chord is essentially a callback for a group of tasks.

The body is applied with the return values of all the header tasks as a list.


The chord:

>>> res = chord([add.s(2, 2), add.s(4, 4)])(sum_task.s())

is effectively \Sigma ((2 + 2) + (4 + 4)):

>>> res.get()
celery.signature(varies, *args, **kwargs)[源代码]

Create new signature.

  • if the first argument is a signature already then it’s cloned.
  • if the first argument is a dict, then a Signature version is returned.
返回:The resulting signature.
class celery.Signature(task=None, args=None, kwargs=None, options=None, type=None, subtask_type=None, immutable=False, app=None, **ex)[源代码]

Task Signature.

Class that wraps the arguments and execution options for a single task invocation.

Used as the parts in a group and other constructs, or to pass tasks around as callbacks while being compatible with serializers with a strict type subset.

Signatures can also be created from tasks:

  • Using the .signature() method that has the same signature as Task.apply_async:

    >>> add.signature(args=(1,), kwargs={'kw': 2}, options={})
  • or the .s() shortcut that works for star arguments:

    >>> add.s(1, kw=2)
  • the .s() shortcut does not allow you to specify execution options but there’s a chaning .set method that returns the signature:

    >>> add.s(2, 2).set(countdown=10).set(expires=30).delay()


You should use signature() to create new signatures. The Signature class is the type returned by that function and should be used for isinstance checks for signatures.


Canvas: Designing Work-flows for the complete guide.

  • task (Task, str) – Either a task class/instance, or the name of a task.
  • args (Tuple) – Positional arguments to apply.
  • kwargs (Dict) – Keyword arguments to apply.
  • options (Dict) – Additional options to Task.apply_async().


If the first argument is a dict, the other arguments will be ignored and the values in the dict will be used instead:

>>> s = signature('tasks.add', args=(2, 2))
>>> signature(s)
{'task': 'tasks.add', args=(2, 2), kwargs={}, options={}}



The currently set app for this thread.


The task currently being executed (only set in the worker, or when eager/apply is used).