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

How to use task decorator in django celery

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

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())