Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

python - Celery - Get task id for current task

How can I get the task_id value for a task from within the task? Here's my code:

from celery.decorators import task
from django.core.cache import cache

@task
def do_job(path):
    "Performs an operation on a file"

    # ... Code to perform the operation ...

    cache.set(current_task_id, operation_results)

The idea is that when I create a new instance of the task, I retrieve the task_id from the task object. I then use the task id to determine whether the task has completed. I don't want to keep track of the task by the path value because the file is "cleaned up" after the task completes, and may or may not exist.

In the above example, how would I get the value of current_task_id?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UPDATE: use Balthazar's answer for Celery 3.1+

@task(bind=True)
def do_job(self, path):
   cache.set(self.request.id, operation_results)

Feel free to upvote his answer.

Old answer:

Since Celery 2.2.0, information related to the currently executed task is saved to task.request (it's called ?the context?). So you should get task id from this context (not from keyword arguments, which are deprecated):

@task
def do_job(path):
    cache.set(do_job.request.id, operation_results)

The list of all available fields is documented here: http://celery.readthedocs.org/en/latest/userguide/tasks.html?highlight=requestcontext#context


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...