异步任务执行的时候对于用户来说总是会出现再次尝试,第二次查看结果的时候如果能查到任务结果如何那就可以减少好多不必要的查询和重试。Django中可以使用django_celery_results,但是django_celery_results查不到celery_taskmeta表中的数据,只能查询安装了该库以后的任务。所以推荐使用以下方法,简单易懂,可以直接查celery_taskmeta表的数据。

1
2
3
4
from celery.result import AsyncResult
# task_id 为开启异步任务时生成的task_id
task_id = 'd7a3dc7f-b428-4adf-903c-0b11e9ae21ff'
AsyncResult(task_id).status
结果 说明
PENDING 没有执行 or 状态未知
RECEIVED 已接收
STARTED 已启动
SUCCESS 成功
FAILURE 失败
REVOKED 已撤销
REJECTED 被拒绝
RETRY 重试中
  • 源码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    #: Task state is unknown (assumed pending since you know the id).
    PENDING = 'PENDING'
    #: Task was received by a worker (only used in events).
    RECEIVED = 'RECEIVED'
    #: Task was started by a worker (:setting:`task_track_started`).
    STARTED = 'STARTED'
    #: Task succeeded
    SUCCESS = 'SUCCESS'
    #: Task failed
    FAILURE = 'FAILURE'
    #: Task was revoked.
    REVOKED = 'REVOKED'
    #: Task was rejected (only used in events).
    REJECTED = 'REJECTED'
    #: Task is waiting for retry.
    RETRY = 'RETRY'