简体   繁体   中英

How to use task decorator in django celery

I have this task in this setup that needs to be run periodically:

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="*"),
    },
}


I'm getting this error

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'

I'm not sure if i put the decorator in the correct place

In case anyone has a similar problem. I found a way to make it work.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM