【发布时间】:2019-07-10 02:02:33
【问题描述】:
我必须安排一个任务在每周一到周六运行。我下载了 django-celery 来完成任务。我按照Celery site 上的教程进行操作,并使用并查看了一些堆栈溢出帖子,例如:here & here
我对上述帖子和这两个很棒的教程进行了混合搭配:Rhatore 和 Freitas
这是我的文件夹结构:
Application
| apps
| app1
| __init__.py
| tasks.py
| urls.py
| views.py
| Application
| __init__.py
| celery.py
| settings.py
| urls.py
| wsgi.py
Settings.py
INSTALLED_APPS = [
'django_celery_beat',
'apps.app1',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
CELERY_BROKER_URL = 'amqp://localhost'
CELERY_RESULT_BACKEND = 'amqp://localhost'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'UTC'
__init__.py在init下的Application
from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app
from .celery import app as celery_app
__all__ = ('celery_app',)
celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Application.settings')
app = Celery('Application')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
tasks.py - 为简单起见,我将任务简化为简单的打印命令
from celery import shared_task
from celery.utils.log import get_task_logger
from celery.schedules import crontab
from celery.task import periodic_task
from celeryapp.emails import send_feedback_email
from django.http import HttpResponse
from .models import *
logger=get_task_logger(__name__)
@periodic_task(run_every=crontab(hour=21, minute=32, day_of_week=0-5))
def simple_print():
print("Hello World!")
我跑了:
celery -A Application -1 info
然后python manage.py runserver
21:32 UTC 过去了,它没有打印。我希望根据 tasks.py 中指定的任务在 21:32 UTC 在终端中看到“Hello World”。它没有打印。
我也跑了:
celery -A Application worker -l info
celery -A Application beat -l info
python manage.py runserver
在不同的终端。它没有执行任务。
非常感谢您的指导。
【问题讨论】:
-
您能否更详细地解释您的问题。或者也许“它没有打印” - 是对问题的解释?你期待什么?
-
亚历克斯感谢您的提问。我编辑了我的问题。基本上,我要做的是使用 cron 将“Hello World”打印到终端。
-
如果您将
print替换为文件-write或logging.info或者数据库插入 - 您会得到“Hello World!”吗? -
我试过 f = open("myfile.txt", "x") 并没有创建文件。