Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Celery - how to get task name by task id?

Celery - bottom line: I want to get the task name by using the task id (I don't have a task object)

Suppose I have this code:

res = chain(add.s(4,5), add.s(10)).delay()
cache.save_task_id(res.task_id)

And then in some other place:

task_id = cache.get_task_ids()[0]
task_name = get_task_name_by_id(task_id) #how?
print(f'Some information about the task status of: {task_name}')

I know I can get the task name if I have a task object, like here: celery: get function name by task id?. But I don't have a task object (perhaps it can be created by the task_id or by some other way? I didn't see anything related to that in the docs).

In addition, I don't want to save in the cache the task name. (Suppose I have a very long chain/other celery primitives, I don't want to save all their names/task_ids. Just the last task_id should be enough to get all the information regarding all the tasks, using .parents, etc)

I looked at all the relevant methods of AsyncResult and AsyncResult.Backend objects. The only thing that seemed relevant is backend.get_task_meta(task_id), but that doesn't contain the task name. Thanks in advance

PS: AsyncResult.name always returns None:

result = AsyncResult(task_id, app=celery_app)
result.name #Returns None
result.args #Also returns None
like image 591
RNE Avatar asked Sep 15 '20 12:09

RNE


1 Answers

Finally found an answer. For anyone wondering: You can solve this by enabling result_extended = True in your celery config. Then:

result = AsyncResult(task_id, app=celery_app)
result.task_name #tasks.add
like image 113
RNE Avatar answered Sep 26 '22 09:09

RNE