Celery和Django的定期任务

时间:2014-01-30 18:46:47

标签: python django celery periodic-task

我遇到了使用Celery 3.1.8,Django 1.6.1和RabbitMQ运行的定期任务的麻烦。我对当前的文档有点困惑,因为据我所知,不再需要django-celery来让Celery与Django一起运行。我有一种感觉,我没有正确地运行工作人员,但在寻找SO和google搜索解决方案之后,我需要帮助。有人能指出我正确的方向吗?

settings.py(不确定我是否需要这个,因为我的任务上有@periodic_task装饰器)

CELERYBEAT_SCHEDULE = {
    'add-every-30-seconds': {
        'task': 'tasks.send_test_email',
        'schedule': datetime.timedelta(seconds=30)
    },
}

我的应用(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', 'app.settings')

app = Celery('app',
             broker='amqp://',
             backend='amqp://',
             include=['app.tasks'])


app.conf.update(
    CELERY_TASK_RESULT_EXPIRES=3600,
    CELERY_TIMEZONE='Europe/Oslo',
    )

if __name__ == '__main__':
    app.start()

# 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 __future__ import absolute_import
from celery.task import periodic_task
import datetime

@periodic_task(run_every=datetime.timedelta(minutes=1))
def send_test_email():
    print "This is a periodic task from celery"

在命令行中,我正在执行worker:

celery worker -A app -l info
celery beat

1 个答案:

答案 0 :(得分:1)

其他一些解决方案是使用@periodic_task celery decorator

from celery.schedules import crontab

@periodic_task(run_every=crontab(minute=0, hour=1))
def my_task():
    print 'my_task'