我正在尝试在 Celery 中设置一个每 3 秒运行一次的虚拟任务,但到目前为止收效甚微。这是我得到的输出:
我已将芹菜设置如下:
在settings.py中:
from datetime import timedelta
BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'UTC'
CELERY_IMPORTS = ("api.tasks")
CELERYBEAT_SCHEDULE = {
'add_job': {
'task': 'add_job',
'schedule': timedelta(seconds=3),
'args': (16, 16)
},
}
CELERY_TIMEZONE = 'UTC'
在celery.py:
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blogpodapi.settings')
app = Celery(
'blogpodapi',
)
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
在 tasks.py
from celery.task import task
@task(name='add_job')
def add_job(x, y):
r = x + y
print "task arguments: {x}, {y}".format(x=x, y=y)
print "task result: {r}".format(r=r)
return r
我的设置方式是否做错了什么?
仅回答,因为这是我在
CELERYBEAT_SCHEDULE
上搜索时的第一个结果。
它对我不起作用的原因是因为它应该是
CELERY_BEAT_SCHEDULE
好吧,我看到的一个非常基本的错误是,您在
settings.py
中提到的大多数设置都需要进入 celery.py
特别是
CELERYBEAT_SCHEDULE
你做的一切都是正确的,只是你的 Celery 正在等待任务,它永远不会收到任务,因为它是从 celery.py 而不是从 settings.py 读取的。因此什么也没有发生。
请参阅我的 celery.py 以及 settings.py 以供参考。
celery.py -> https://github.com/amyth/hammer/blob/master/config/celery.py
settings.py -> https://github.com/amyth/hammer/blob/master/config/settings.py
我使用了crontab,因为我想在一天中的特定时间执行任务。所以你不需要担心它。您的非常适合您想做的事情。
此外,无论您关注 celery 的任何博客或教程,请再次检查这些设置到底需要什么以及您是否需要所有这些设置。
至于为什么你的任务没有运行:它没有注册。如果是这样,Celery 工作程序启动时的输出将会有所不同 - 它将包含以下两行(至少):
[tasks]
. add_job
我是芹菜新手。就我而言,我必须跑步才能使其发挥作用。
celery -A myapp.celery_app beat -l debug