Celery - Activate a task via command line or HTTP requests
Asked Answered
O

2

7

I have a predefined celery task in my code, say my_proj.tasks.my_celery_task

I want to activate the task via the command line/HTTP request (not via my application).

I searched the documents (saw flower and curl options) but there isn't a real good example of calling a predefined task there. How to achieve this?

Onestep answered 3/11, 2014 at 8:10 Comment(0)
R
18

Assuming you have installed Celery with Rabbitmq, here is a simple example.

Define a task: my_app.py

from celery import Celery

app = Celery('tasks', backend='amqp', broker='amqp://')

@app.task
def add(x, y):
    return x + y

Start a worker:

celery worker -l info -A my_app

Start flower

flower -A my_app

Add a task to queue via command line

curl -X POST -d '{"args":[1,2]}' http://localhost:5555/api/task/async-apply/my_app.add

or via requests

import requests, json
api_root = 'http://localhost:5555/api'
task_api = '{}/task'.format(api_root)
args = {'args': [1, 2]}
url = '{}/async-apply/my_app.add'.format(task_api)
print(url)
resp = requests.post(url, data=json.dumps(args))
reply = resp.json()
reply
Raphaelraphaela answered 3/11, 2014 at 8:53 Comment(2)
Thanks! I'm trying exactly that but it doesn't return (as if it's stack). Is there anyway to set a timeout to check why it's stack? I'm using the CURL option.Onestep
You can set timeout. A simple example to set it is given here nbviewer.ipython.org/github/mher/flower/blob/master/docs/…Raphaelraphaela
P
15

You can use the celery command line

Call a task

# Positional arguments
celery call my_celery_task --args='[1,2]' --broker <broker_url>
# Keyword arguments
celery call my_celery_task --kwargs='{"x":1, "y":2}' --broker <broker_url>
# Returns the task-id

Get the result

celery result <task_id> --result-backend <backend_url>

You should select the same broker and backend set in your celery application.

Prosecution answered 6/4, 2020 at 14:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.