Home > front end >  How to Get the Task Status and Result of a Celery Task Type When Multiple Tasks Are Defined?
How to Get the Task Status and Result of a Celery Task Type When Multiple Tasks Are Defined?

Time:04-26

Typically I send an asynchronous task with .apply_async method of the Promise defined, and then I use the taskid on the AsyncResult method of the same object to get task status, and eventually, result.

But this requires me to know the exact type of task when more than one tasks are defined in the same deployment. Is there any way to circumvent this, when I can know the task status and result (if available) without knowing the exact task?

For example, take this example celery master node code.

#!/usr/bin/env python3
# encoding:utf-8

"""Define the tasks in this file."""
from celery import Celery

redis_host: str = 'redis://localhost:6379/0'

celery = Celery(main='test', broker=redis_host,
                backend=redis_host)


celery.conf.CELERY_TASK_SERIALIZER = 'pickle'
celery.conf.CELERY_RESULT_SERIALIZER = 'pickle'
celery.conf.CELERY_ACCEPT_CONTENT = {'json', 'pickle'}

# pylint: disable=unused-argument


@celery.task(bind=True)
def add(self, x: float, y: float) -> float:
    """Add two numbers."""
    return x   y


@celery.task(bind=True)
def multiply(self, x: float, y: float) -> float:
    """Multiply two numbers."""
    return x * y

When I call something like this in a different module

task1=add.apply_async(args=[2, 3]).id
task2=multiply.apply_async(args=[2, 3]).id

I get two uuids for the tasks. But when checking back the task status, I need to know which method (add or multiply) is associated with that task id, since I have to call the method on the corresponding object, like this.

status: str = add.AsyncResult(task_id=task1).state

My question is how can I fetch the state and result armed only with the task id without knowing whether the task belongs add, multiply or any other category defined.

CodePudding user response:

id and state are just properties of the AsyncResult objects. If you looked at documentation for the AsyncResult class, you would find the name property which is exactly what you are asking for.

  • Related