[Python] How to get the estimated remaining time of an already started Celery task?

Discussão em 'Python' iniciado por Stack, Outubro 5, 2024.

  1. Stack

    Stack Membro Participativo

    I am using django with Celery and redis. I would like that when a user initiates a Celery task my app estimates the amount of time left until the task is completed(so that I can, for example, represent this data to the frontend as a progress bar).

    For example, given this polling function:

    views.py:

    @csrf_protect
    def initiate_task(request):
    task = new_celery_task.delay(parmeter_1, parametr_2)

    @csrf_protect
    def poll_task_status(request, task_id): #task_id provided by frontend

    import base64
    task_result = AsyncResult(task_id)

    if task_result.ready():
    try:
    ...

    response_data = {
    'status': 'completed',
    }

    except Task.DoesNotExist:
    return JsonResponse({'status': 'error', 'message': 'There has been an error'}, status=404)

    elif task_result.state == 'REVOKED':
    return JsonResponse({'status': 'terminated', 'message': 'Task was terminated'})

    else:
    #add code to calculate estimated remaining time here
    remaining_time_est = estimate_remaining_time() #estimate task by id
    return JsonResponse({'status': 'pending'
    #add code to return estimated remaining time here
    'est_remaining_time':remaining_time_est
    })


    and task:

    task.py:

    app = Celery('myapp')#
    @app.task
    def new_celery_task(arg_1, arg_2):
    #complete task


    How would I estimate the remaining time left on an initiated task?

    Continue reading...

Compartilhe esta Página