This document describes an older version of Celery (2.2). For the latest stable version please go here.
Task base class.
When called tasks apply the run() method. This method must be defined by all tasks (that is unless the __call__() method is overridden).
Get AsyncResult instance for this kind of task.
Parameters: | task_id – Task id to get result for. |
---|
The tasks max restart limit has been exceeded.
If True the task is an abstract base class.
If disabled the worker will not forward magic keyword arguments. Deprecated and scheduled for removal in v3.0.
When enabled messages for this task will be acknowledged after the task has been executed, and not just before which is the default behavior.
Please note that this means the task may be executed twice if the worker crashes mid execution (which may be acceptable for some applications).
The application default can be overriden with the CELERY_ACKS_LATE setting.
Handler called after the task returns.
Parameters: |
|
---|
The return value of this handler is ignored.
The application instance associated with this task class.
Execute this task locally, by blocking until the task returns.
Parameters: |
|
---|
:rtype celery.result.EagerResult:
Apply tasks asynchronously by sending a message.
Parameters: |
|
---|
Note
If the CELERY_ALWAYS_EAGER setting is set, it will be replaced by a local apply() call instead.
If disabled this task won’t be registered automatically.
The result store backend used for this task.
Default time in seconds before a retry of the task should be executed. 3 minutes by default.
Star argument version of apply_async().
Does not support the extra options enabled by apply_async().
Parameters: |
|
---|
:returns celery.result.AsyncResult:
Override the apps default delivery mode for this task. Default is “persistent”, but you can change this to “transient”, which means messages will be lost if the broker is restarted. Consult your broker manual for any additional delivery modes.
List of exception types to send error e-mails for.
Establish a connection to the message broker.
Overrides the apps default exchange for this task.
Overrides the apps default exchange type for this task.
The method the worker calls to execute the task.
Parameters: |
|
---|
Default task expiry time.
Get message consumer.
:rtype kombu.messaging.Consumer:
Warning
If you don’t specify a connection, one will automatically be established for you, in that case you need to close this connection after use:
>>> consumer = self.get_consumer()
>>> # do something with consumer
>>> consumer.close()
>>> consumer.connection.close()
Get task-aware logger object.
Get a celery task message publisher.
:rtype TaskPublisher:
Warning
If you don’t specify a connection, one will automatically be established for you, in that case you need to close this connection after use:
>>> publisher = self.get_publisher()
>>> # ... do something with publisher
>>> publisher.connection.close()
or used as a context:
>>> with self.get_publisher() as publisher:
... # ... do something with publisher
If enabled the worker will not store task state and return values for this task. Defaults to the CELERY_IGNORE_RESULT setting.
Request immediate delivery.
Mandatory message routing.
Maximum number of retries before giving up. If set to None, it will never stop retrying.
Name of the task.
Error handler.
This is run by the worker when the task fails.
Parameters: |
|
---|
The return value of this handler is ignored.
Retry handler.
This is run by the worker when the task is to be retried.
Parameters: |
|
---|
The return value of this handler is ignored.
Success handler.
Run by the worker if the task executes successfully.
Parameters: |
|
---|
The return value of this handler is ignored.
Default message priority. A number between 0 to 9, where 0 is the highest. Note that RabbitMQ does not support priorities.
Destination queue. The queue needs to exist in CELERY_QUEUES. The routing_key, exchange and exchange_type attributes will be ignored if this is set.
Rate limit for this task type. Examples: None (no rate limit), “100/s” (hundred tasks a second), “100/m” (hundred tasks a minute),`”100/h”` (hundred tasks an hour)
Request context (set when task is applied).
Retry the task.
Parameters: |
|
---|---|
Raises celery.exceptions.RetryTaskError: | |
To tell the worker that the task has been re-sent for retry. This always happens, unless the throw keyword argument has been explicitly set to False, and is considered normal operation. |
Example
>>> @task
>>> def tweet(auth, message):
... twitter = Twitter(oauth=auth)
... try:
... twitter.post_status_update(message)
... except twitter.FailWhale, exc:
... # Retry in 5 minutes.
... return tweet.retry(countdown=60 * 5, exc=exc)
Although the task will never return above as retry raises an exception to notify the worker, we use return in front of the retry to convey that the rest of the block will not be executed.
Overrides the apps default routing_key for this task.
The body of the task executed by workers.
If enabled an e-mail will be sent to ADMINS whenever a task of this type fails.
The name of a serializer that are registered with kombu.serialization.registry. Default is “pickle”.
When enabled errors will be stored even if the task is otherwise configured to ignore results.
Returns subtask object for this task, wrapping arguments and execution options for a single task invocation.
If enabled the task will report its status as “started” when the task is executed by a worker. Disabled by default as the normal behaviour is to not report that level of granularity. Tasks are either pending, finished, or waiting to be retried.
Having a “started” status can be useful for when there are long running tasks and there is a need to report which task is currently running.
The application default can be overridden using the CELERY_TRACK_STARTED setting.
The type of task (no longer used).
Update task state.
Parameters: |
|
---|
A periodic task is a task that behaves like a cron job.
Results of periodic tasks are not stored by default.
REQUIRED Defines how often the task is run (its interval), it can be a timedelta object, a crontab object or an integer specifying the time in seconds.
If set to True, run times are relative to the time when the server was started. This was the previous behaviour, periodic tasks are now scheduled by the clock.
Raises NotImplementedError: | |
---|---|
if the run_every attribute is not defined. |
Example
>>> from celery.task import tasks, PeriodicTask
>>> from datetime import timedelta
>>> class EveryThirtySecondsTask(PeriodicTask):
... run_every = timedelta(seconds=30)
...
... def run(self, **kwargs):
... logger = self.get_logger(**kwargs)
... logger.info("Execute every 30 seconds")
>>> from celery.task import PeriodicTask
>>> from celery.schedules import crontab
>>> class EveryMondayMorningTask(PeriodicTask):
... run_every = crontab(hour=7, minute=30, day_of_week=1)
...
... def run(self, **kwargs):
... logger = self.get_logger(**kwargs)
... logger.info("Execute every Monday at 7:30AM.")
>>> class EveryMorningTask(PeriodicTask):
... run_every = crontab(hours=7, minute=30)
...
... def run(self, **kwargs):
... logger = self.get_logger(**kwargs)
... logger.info("Execute every day at 7:30AM.")
>>> class EveryQuarterPastTheHourTask(PeriodicTask):
... run_every = crontab(minute=15)
...
... def run(self, **kwargs):
... logger = self.get_logger(**kwargs)
... logger.info("Execute every 0:15 past the hour every day.")
Returns tuple of two items (is_due, next_time_to_run), where next time to run is in seconds.
See celery.schedules.schedule.is_due() for more information.
Returns when the periodic task should run next as a timedelta.
Convert timedelta to seconds.
Doesn’t account for negative timedeltas.
Metaclass for tasks.
Automatically registers the task in the task registry, except if the abstract attribute is set.
If no name attribute is provided, the name is automatically set to the name of the module it was defined in, and the class name.