Tasks¶
The Task framework provides the contract and plumbing for background work, not the engine that runs it. The Tasks API defines how work is described, queued, and tracked, but leaves actual execution to external infrastructure.
Task definition¶
The task decorator¶
- task(*, priority=0, queue_name='default', backend='default', takes_context=False)[source]¶
The
@taskdecorator defines aTaskinstance. This has the following optional arguments:priority: Sets thepriorityof theTask. Defaults to 0.queue_name: Sets thequeue_nameof theTask. Defaults to"default".backend: Sets thebackendof theTask. Defaults to"default".takes_context: contrôle si la fonctionTaskaccepte un objetTaskContext. VautFalsepar défaut. Voir Contexte des tâches pour plus de détails.
Si la tâche définie n’est pas valable selon le moteur, une exception
InvalidTaskest générée.Voir définition des tâches pour des exemples d’utilisation.
Task¶
- class Task[source]¶
Représente une tâche à exécuter en arrière-plan. Les tâches doivent être définies par le décorateur func:task.
Les attributs de
Taskne peuvent pas être modifiés. Voir :ref:modification des tâches <modifying-tasks>` pour plus de détails.- priority¶
La priorité de
Task. Les priorités doivent se situer entre -100 et 100, où un plus grand nombre signifie une priorité plus haute et va donc s’exécuter plus rapidement.Le moteur doit avoir l’attribut
supports_priorityàTruepour pouvoir utiliser cette fonctionnalité.
- backend¶
L’alias du moteur pour lequel la tâche
Taskdoit être placée en file d’attente. Cela doit correspondre à un moteur défini dansBACKEND.
- queue_name¶
Le nom de la file d’attente à laquelle la tâche sera attribuée. Par défaut, c’est
"default". Cela doit correspondre à une file d’attente définie dansQUEUES, sauf siQUEUESest défini à[].
- run_after¶
The earliest time the
Taskwill be executed. This can be atimedelta, which is used relative to the current time, a timezone-awaredatetime, orNoneif not constrained. Defaults toNone.The backend must have
supports_deferset toTrueto use this feature. Otherwise,InvalidTaskis raised.
- using(*, priority=None, backend=None, queue_name=None, run_after=None)[source]¶
Crée une nouvelle
Taskavec des valeurs par défaut modifiées. La tâche existante n’est pas touchée.usingpermet de modifier les attributs suivants :Voir modification des tâches pour des exemples d’utilisation.
- enqueue(*args, **kwargs)[source]¶
Enqueues the
Taskto theTaskbackend for later execution.Arguments are passed to the
Task’s function after a round-trip through ajson.dumps()/json.loads()cycle. Hence, all arguments must be JSON-serializable and preserve their type after the round-trip.If the
Taskis not valid according to the backend,InvalidTaskis raised.See enqueueing Tasks for usage examples.
- get_result(result_id)[source]¶
Retrieves a result by its id.
If the result does not exist,
TaskResultDoesNotExistis raised. If the result is not the same type as the current Task,TaskResultMismatchis raised. If the backend does not supportget_result(),NotImplementedErroris raised.
- aget_result(*args, **kwargs)¶
The
asyncvariant ofget_result.
Contexte des tâches¶
- class TaskContext[source]¶
Contains context for the running
Task. Context only passed to aTaskif it was defined withtakes_context=True.Attributes of
TaskContextcannot be modified.- task_result¶
The
TaskResultcurrently being run.
Task results¶
- class TaskResultStatus[source]¶
An Enum representing the status of a
TaskResult.
- class TaskResult[source]¶
The
TaskResultstores the information about a specific execution of aTask.Attributes of
TaskResultcannot be modified.- id¶
A unique identifier for the result, which can be passed to
Task.get_result().The format of the id will depend on the backend being used. Task result ids are always strings less than 64 characters.
See Task results for more details.
- enqueued_at¶
The time when the
Taskwas enqueued.
- started_at¶
The time when the
Taskbegan execution, on its first attempt.
- last_attempted_at¶
The time when the most recent
Taskrun began execution.
- finished_at¶
The time when the
Taskfinished execution, whether it failed or succeeded.
- backend¶
The backend the result is from.
- return_value[source]¶
The return value from the
Taskfunction.If the
Taskdid not finish successfully,ValueErroris raised.See return values for usage examples.
- arefresh()¶
The
asyncvariant ofTaskResult.refresh().
- attempts[source]¶
The number of times the Task has been run.
If the task is currently running, it does not count as an attempt.
- worker_ids¶
The ids of the workers which have executed the Task.
Task errors¶
Backends¶
Backends handle how Tasks are stored and executed. All backends share a common
interface defined by BaseTaskBackend, which specifies the core methods for
enqueueing Tasks and retrieving results.
Base backend¶
- class BaseTaskBackend[source]¶
BaseTaskBackendis the parent class for all Task backends.- options¶
A dictionary of extra parameters for the Task backend. These are provided using the
OPTIONSsetting.
- enqueue(task, args, kwargs)[source]¶
Task backends which subclass
BaseTaskBackendshould implement this method as a minimum.When implemented,
enqueue()enqueues thetask, aTaskinstance, for later execution.argsare the positional arguments andkwargsare the keyword arguments to be passed to thetask. Returns aTaskResult.
- aenqueue(task, args, kwargs)¶
The
asyncvariant ofBaseTaskBackend.enqueue().
- get_result(result_id)[source]¶
Retrieve a result by its id. If the result does not exist,
TaskResultDoesNotExistis raised.If the backend does not support
get_result(),NotImplementedErroris raised.
- aget_result(result_id)¶
The
asyncvariant ofBaseTaskBackend.get_result().
- validate_task(task)[source]¶
Validates whether the provided
Taskis able to be enqueued using the backend. If the Task is not valid,InvalidTaskis raised.
Feature flags¶
Some backends may not support all features Django provides. It’s possible to identify the supported functionality of a backend, and potentially change behavior accordingly.
- BaseTaskBackend.supports_defer¶
Whether the backend supports enqueueing Tasks to be executed after a specific time using the
run_afterattribute.
- BaseTaskBackend.supports_async_task¶
Whether the backend supports enqueueing async functions (coroutines).
- BaseTaskBackend.supports_get_result¶
Whether the backend supports retrieving
Taskresults from another thread after they have been enqueued.
- BaseTaskBackend.supports_priority¶
Whether the backend supports executing Tasks as ordered by their
priority.
The below table notes which of the built-in backends support which features:
Feature |
||
|---|---|---|
Oui |
Non |
|
Oui |
Oui |
|
Non |
No [1] |
|
Yes [2] |
Yes [3] |
Available backends¶
Django includes only development and testing backends. These support local execution and inspection, for production ready backends refer to Configuration d’un moteur de tâches.
Immediate backend¶
- class ImmediateBackend[source]¶
The immediate backend executes Tasks immediately, rather than in the background.
Le moteur bidon¶
Exceptions¶
- exception InvalidTaskBackend[source]¶
Raised when the requested
BaseTaskBackendis invalid.
- exception TaskResultDoesNotExist[source]¶
Raised by
get_result()when the providedresult_iddoes not exist.
- exception TaskResultMismatch[source]¶
Raised by
get_result()when the providedresult_idis for a different Task than the current Task.
Notes de bas de page