如何在django-celene中使用任务装饰器



我在这个设置中有一个需要定期运行的任务:

app.tasks.sum.py

import sys
from celery.decorators import periodic_task
class Sum:
@periodic_task
def __call__(self, a, b):
return a + b
sys.modules[__name__] = Sum()

project.settings.py:

CELERY_BROKER_URL = 'redis://user:password@redis:6379/'
CELERY_RESULT_BACKEND = 'redis://user:password@redis:6379/'
CELERY_BEAT_SCHEDULE = {
"sum": {
"task": "app.tasks.sum",
"schedule": crontab(minute="*"),
},
}

我收到这个错误

Scheduler: Sending due task sum(app.tasks.sum)
The message has been ignored and discarded.
Did you remember to import the module containing this task?
Or maybe you're using relative imports?
Please see
http://docs.celeryq.org/en/latest/internals/protocol.html
for more information.
The full contents of the message body was:
b'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b)
Traceback (most recent call last):
File "/opt/bitnami/python/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 562, in on_task_received
strategy = strategies[type_]
KeyError: 'app.tasks.sum'

我不确定我是否把装饰器放在正确的位置

如果有人遇到类似的问题。我找到了一种让它发挥作用的方法。

app.tasks.sum.py:

import sys
# project is the name of the django project
# celery_app is from the celery.py that you have created which contains the celery app instance of the project
from project import celery_app
class Sum(celery_app.Task):
name = __name__
def __call__(self, a, b):
return a + b
sys.modules[__name__] = celery_app.register_task(Sum())

相关内容

  • 没有找到相关文章

最新更新