GuillaumeA
GuillaumeA

Reputation: 3545

How to know if a celery task has already been launched

I have a Flask application whithin which I can start a celery task. This task is kind of a daemon that I would like to launch only once. So when it is launched, all I want is monitoring its status, display some message from whithin the task etc. This is all working well.

What I cannot figure how to do it, is how, in the flask application, can I get the task id once it is launched. When I start the task I can do

@main.route('/start', methods=['POST'])
def start():
    task = long_task.apply_async()
    # from here I know the id with 'task.id'
    return jsonify({}), 202

so I have the id of the task.

Now, imagine I restart the celery server or I kill the task, how can I check if such a task is running ? And if it is running, how can I retrieve its id ?

What I tried for now: Run a celery server, run a flask application, start a celery task from whithin the flask application, reload the main page to see if I can retrieve the task id:

@main.route('/', methods=['GET', 'POST'])
def index():
    """Renders the home page."""
    _t = celery.current_task
    if _t is not None:
        t_id = toto.request.id
    return render_template('main/index.html', title='Main page')

but the _t variable is always None even when a celery task is running.

Upvotes: 0

Views: 1153

Answers (1)

ItayB
ItayB

Reputation: 11337

One way to do it (via celery API) would be to check the control client. It can help you to inspect reserved tasks, active tasks and so on..

i = app.control.inspect()
i.reserved()

#output:
[{'worker1.example.com':
    [{'name': 'tasks. long_task',
      'id': '32666e9b-809c-41fa-8e93-5ae0c80afbbf',
      'args': '(8,)',
      'kwargs': '{}'}]}]

You can iterate over this task array to find (by task name) if your task is already running and retrieve it's state).

for more info: http://docs.celeryproject.org/en/latest/userguide/workers.html#dump-of-reserved-tasks

Second option (which I think is a bad idea) might be to check the backend directly: if this Redis used only as celery backend and you have only this task running - you can find all the keys (uuid is part of the key) and the task status will be part of the value.

Upvotes: 2

Related Questions