我想使用Celery在Django中启动一个定期任务。以下是我的项目的相关部分:
# celery.py
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookProjectSetting.settings')
app = Celery('bookProjectSetting')
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print(f'Request: {self.request!r}')__init__.py如下所示:
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
__all__ = ('celery_app',)我的books应用程序文件夹中的tasks.py文件如下所示:
from books.models import Book
from celery.schedules import crontab
from celery.decorators import periodic_task
@periodic_task(
run_every=(crontab(minute='*/10')),
name="update_life_time_of_books",
ignore_result=True)
def update_life_time_of_books():
# do sth. 我还将redis设置为代理,并安装了django-celery-beat内容。但是当我通过以下命令运行worker时:
celery -A bookProjectSetting beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler然后我得到以下错误:
File "/home/ac3l1k/Desktop/PROJECT/simpleDjangoProjects/bookProject/env/lib/python3.8/site-packages/celery/local.py", line 403, in _compat_periodic_task_decorator
from celery.task import periodic_task
ModuleNotFoundError: No module named 'celery.task'从错误中,我假设装饰器出了问题,但我不知道为什么。希望有人能帮上忙。
Thnks in advance :=)
注意:以下是我的requirements.txt文件的内容,供版本参考
$ pip freeze
amqp==5.0.1
asgiref==3.2.10
billiard==3.6.3.0
celery==5.0.1
click==7.1.2
click-didyoumean==0.0.3
click-repl==0.1.6
Django==3.1.2
django-celery-beat==2.1.0
django-timezone-field==4.0
djangorestframework==3.12.1
kombu==5.0.2
prompt-toolkit==3.0.8
python-crontab==2.5.1
python-dateutil==2.8.1
pytz==2020.1
redis==3.5.3
six==1.15.0
sqlparse==0.4.1
vine==5.0.0
wcwidth==0.2.5发布于 2021-03-10 16:17:52
"task“不再是5.x版本,您可以使用4.x版本
编辑了空间
发布于 2020-10-24 08:48:20
根据我对这个问题的理解,他们弃用了这个功能:https://github.com/celery/celery/issues/6406
现在,您似乎需要使用它来制定计划任务:
https://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html?highlight=periodic
https://stackoverflow.com/questions/64483648
复制相似问题