Django 和 Celery - ModuleNotFoundError:没有名为 'celery.task' 的模块



我想使用CeleryDjango中启动一个周期性任务。以下是我项目的相关部分:

# 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。但是当我通过命令运行工作程序时:

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'

根据这个错误,我认为装饰器出了问题,但我不知道为什么。希望有人能帮忙。

提前通知:=(

注意:这是我的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

;任务";不再是5.x版本您可以使用4.x版

  • pip3卸载芹菜
  • pip3安装芹菜==4.4.2

编辑空间

正如我从这个问题中了解到的那样,他们不赞成使用该功能:https://github.com/celery/celery/issues/6406

现在看来,你需要使用这个来制定计划任务:

https://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html?highlight=periodic

我遇到了这个问题,但我在下面将这个导入与芹菜==5.2.7一起使用

from celery.schedules import crontab

相关内容

  • 没有找到相关文章

最新更新