我的Celery任务正在执行,但它不会在worker中执行

时间:2015-11-13 06:54:48

标签: django celery

我有一个Django应用程序,它有一个api应用程序,允许一个命令请求在返回对请求的响应时触发芹菜任务。 celery任务完成后,它会写入文件。

在我的应用中,我有:

view.py

from api.tasks import *
from codegen import celery_app

def index(request, product_id, amount_to_gen):
    response_data = {}
    generateCodes(product_id, amount_to_gen)
    response_data['result'] = 'success'
    response_data['reason'] = 'The server has successfully received your request'
    return JsonResponse(response_data)

tasks.py

from __future__ import absolute_import
from codegen import celery_app

@celery_app.task()
def generateCodes(product_id, amount_to_gen):
    **code to generate random uniqque codes then put them in a file**

在开始请求之前,我启动Apache并运行

python manage.py celery worker -E

然后发送请求。请求返回响应,但只有在运行generateCodes方法后才会返回响应,并且控制台上没有任何内容显示芹菜工作者。

问题

如何获取返回响应并在后台生成代码文件的请求?

2 个答案:

答案 0 :(得分:1)

generateCodes.apply_async(args=[product_id, amount_to_gen])

如果你像generateCodes(..)那样运行它,它会将它作为普通的阻塞方法运行。

答案 1 :(得分:0)

当您致电generateCodes(product_id, amount_to_gen)时,您将绕过Celery的分布式设施。

为了方便起见,Celery定义了它的任务对象,这样只需调用任务即可调用任务,就像调用Python中的任何函数一样。这被描述为here

  

致电__call__

     

应用支持调用API的对象(例如add(2, 2))意味着任务将在当前进程中执行,而不是由工作程序执行(不会发送消息)。

注意它是如何“不是由工人”。那是你的问题。您必须致电generateCodes.apply_async(product_id, amount_to_gen)让工作人员执行您的任务。

相关问题