我能使用 Celery 而不需要 Django 吗?

12

我有一个API代码,它将任务添加到队列中,然后celery workers消费这些任务。

目前我的代码库相同。但我希望celery workers只有简单的纯Python任务,而没有django代码,因为workers只处理任务并不需要django。这可能吗?

为了启动celery worker,我需要使用这行命令。

celery -A django_project worker --queue high

我应该在django_project那里写什么?

2个回答

13

是的,你可以。Celery是一个通用的异步任务队列。在"djangoproject"的位置上,您将指向您的模块。请参见http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html#application 了解示例。

下面是使用celery的示例项目布局:

project-dir/
    mymodule/
         __init__.py 
         celery.py
         tasks.py
    tests/
    setup.py
    etc, etc (e.g. tox.ini, requirements.txt, project management files)

在我的模块/mymodule/celery.py中:

# -*- coding : utf-8 -*-
from __future__ import absolute_import

from celery import Celery

app = Celery('mymodule',
             broker='amqp://',
             backend='amqp://',
             include=['mymodule.tasks'])

if __name__ == '__main__':
    app.start()

在mymodule/tasks.py中:

from __future__ import absolute_import

from mymodule.celery import app

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

1
celery.py应该包含什么内容? - Karl
现在如何运行这些任务? - Reema Parakh

4
您绝对可以在不使用Django或Flask等web框架的情况下使用Celery。只需创建Celery对象和相应的任务,并运行以下命令即可。
celery -A filename.celery_object_name worker --loglevel=info

稍后,只需运行Python文件。您无需设置任何内容。它可以在任何Web框架下正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,