找出芹菜任务是否存在 [英] Find out whether celery task exists
问题描述
是否可以找出具有特定任务ID的任务是否存在?
Is it possible to find out whether a task with a certain task id exists? When I try to get the status, I will always get pending.
>>> AsyncResult('...').status
'PENDING'
我想知道给定的任务ID是否是真正的芹菜任务ID,而不是随机字符串。我想要不同的结果,具体取决于是否有某个特定ID的有效任务。
I want to know whether a given task id is a real celery task id and not a random string. I want different results depending on whether there is a valid task for a certain id.
过去可能有一个具有相同ID的有效任务,但结果可能已从后端删除。
There may have been a valid task in the past with the same id but the results may have been deleted from the backend.
推荐答案
在任务发送时,Celery不会写状态,这部分是优化
(请参见 http://docs.celeryproject.org/en /latest/userguide/tasks.html#state )。
Celery does not write a state when the task is sent, this is partly an optimization (see http://docs.celeryproject.org/en/latest/userguide/tasks.html#state).
如果确实需要,添加以下内容很简单:
If you really need it, it's simple to add:
from celery import current_app
# `after_task_publish` is available in celery 3.1+
# for older versions use the deprecated `task_sent` signal
from celery.signals import after_task_publish
# when using celery versions older than 4.0, use body instead of headers
@after_task_publish.connect
def update_sent_state(sender=None, headers=None, **kwargs):
# the task may not exist if sent using `send_task` which
# sends tasks by name, so fall back to the default result backend
# if that is the case.
task = current_app.tasks.get(sender)
backend = task.backend if task else current_app.backend
backend.store_result(headers['id'], None, "SENT")
然后,您可以测试PENDING状态以检测任务是否尚未完成(貌似)
已发送:
Then you can test for the PENDING state to detect that a task has not (seemingly) been sent:
>>> result.state != "PENDING"
这篇关于找出芹菜任务是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!