为Django项目中的可重用应用程序创建基于类的Celery任务

时间:2018-07-17 08:43:30

标签: python django task celery django-celery

对于Django项目,创建基于函数的任务非常干净。只需在Django应用中创建task.py并开始编写此示例的任务即可,该示例取自http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html

上的官方celery文档。
from __future__ import absolute_import, unicode_literals
from celery import shared_task

@shared_task
def add(x, y):
    return x + y


@shared_task
def mul(x, y):
    return x * y

但是有时基于功能的任务紧密相关,并且不太可重用。所以我想创建基于类的芹菜任务,该任务已在官方网站上进行了记录。遵循https://github.com/celery/celery/issues/3874之后,我可以创建示例任务,但是我不确定创建基于类的任务的正确方法。

from __future__ import absolute_import, unicode_literals
from celery import shared_task, Task
import time
from celery import current_app


@shared_task
def add(x, y):
    time.sleep(5)
    return x + y


@shared_task
def mul(x, y):
    return x * y

# Sample class based task for testing
class AnotherTask(current_app.Task):
    name = 'tasks.another_task'
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def run(self):
        time.sleep(5)
        return self.x + self.y
# We need to manually register this class based task    
current_app.tasks.register(AnotherTask(3, 4))

我可以调用此任务,但每个调用结果值都相同

(workflow) alok@alok-MacBookAir:~/exp/expdjango/mysite$ ./manage.py shell
Python 3.6.3 (default, Oct  3 2017, 21:45:48) 
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: from polls.tasks import *

In [2]: r = AnotherTask(3,4).delay()

In [3]: r.get()
Out[3]: 7

In [4]: r = AnotherTask(5,6).delay()

In [5]: r.get()
Out[5]: 7

创建和调用基于类的任务是否正确?

1 个答案:

答案 0 :(得分:1)

基于类的任务实际上在每个运行时仅实例化一次。如果要对任务进行参数化,请向run方法中添加参数:

class AnotherTask(current_app.Task):
    name = 'tasks.another_task'

    def run(self, x, y):
        time.sleep(5)
        return x + y

然后您可以这样称呼它:

r = AnotherTask().delay(3, 4)
# Or
r = AnotherTask().apply_async(args=[3, 4])

这在the docs on class based tasks中也有描述,尤其是在instantiation section中。