我的代码中有一个预定义的芹菜任务,比如说my_proj.tasks.my_celery_task
我想通过命令行/HTTP 请求(而不是通过我的应用程序)激活任务。
我搜索了文档(锯花和卷曲选项),但没有一个很好的例子来调用预定义的任务。如何做到这一点?
我的代码中有一个预定义的芹菜任务,比如说my_proj.tasks.my_celery_task
我想通过命令行/HTTP 请求(而不是通过我的应用程序)激活任务。
我搜索了文档(锯花和卷曲选项),但没有一个很好的例子来调用预定义的任务。如何做到这一点?
假设你已经用 Rabbitmq 安装了 Celery,这里是一个简单的例子。
定义一个任务:my_app.py
from celery import Celery
app = Celery('tasks', backend='amqp', broker='amqp://')
@app.task
def add(x, y):
return x + y
启动一个工人:
celery worker -l info -A my_app
开始花
flower -A my_app
通过命令行将任务添加到队列
curl -X POST -d '{"args":[1,2]}' http://localhost:5555/api/task/async-apply/my_app.add
或通过请求
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
您可以使用 celery 命令行
# 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
celery result <task_id> --result-backend <backend_url>
您应该在 celery 应用程序中选择相同的代理和后端集。