【发布时间】:2019-11-09 14:00:24
【问题描述】:
我正在尝试创建我的第一个 Celery 任务。该任务将每隔一分钟向同一个人发送相同的电子邮件。
根据文档,我在项目中创建了第一个任务。
from __future__ import absolute_import, unicode_literals
from celery import shared_task
from django.core.mail import send_mail
@shared_task
def send_message():
to = ['test@test.com', ]
send_mail('TEST TOPIC',
'TEST MESSAGE',
'test@test.com',
to)
然后,在我项目的 ja 文件夹中,添加 celery.py 文件,如下所示:
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings
from celery.schedules import crontab
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_rama.settings')
app = Celery('app_rama')
# 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')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks(settings.INSTALLED_APPS)
app.conf.beat_schedule = {
'send-message-every-single-minute': {
'task': 'app.tasks.send_message',
'schedule': crontab(), # change to `crontab(minute=0, hour=0)` if you want it to run daily at midnight
},
}
然后在我的项目的__int__.py文件中添加:
from __future__ import absolute_import, unicode_literals
# 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',)
我尝试做的最后一件事是运行命令:
celery -A app_rama worker -l info
然后我收到以下错误:
[2019-06-27 16:01:26,750: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [WinError 10061]
我尝试了论坛上的许多解决方案,但没有找到正确的解决方案。 在我的 settings.py 文件中添加以下设置也没有帮助我:
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
如何解决此错误,以便我的任务在应用程序的后台运行?
【问题讨论】:
标签: django celery django-celery