In celery 3.1, making django periodic task

谁说我不能喝 提交于 2019-11-28 15:59:47

I assume you've already read the django section from the docs, but have you seen this example project?

It doesn't use the scheduler but if you add this to settings.py:

from __future__ import absolute_import

from celery.schedules import crontab


CELERYBEAT_SCHEDULE = {
    # crontab(hour=0, minute=0, day_of_week='saturday')
    'schedule-name': {  # example: 'file-backup' 
        'task': 'some_django_app.tasks....',  # example: 'files.tasks.cleanup' 
        'schedule': crontab(...)
    },
}

# if you want to place the schedule file relative to your project or something:
CELERYBEAT_SCHEDULE_FILENAME = "some/path/and/filename"

Now for the commands, forget about manage.py, just type celery directly:

-B enables celery beat as always.

-A specifies the name of the celery app. Note this line in the celery.py of the example project: app = Celery('proj')

celery -A proj worker -B -l info

'django-celery' is not required, install it ONLY if you need to manage the schedule from the admin, or if you want to store task results in the DB through django's ORM:

INSTALLED_APPS += ('djcelery',)

# store schedule in the DB:
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'

You can use django-celery application: https://pypi.python.org/pypi/django-celery

Installation:

pip install django-celery

To enable django-celery for your project you need to add djcelery to INSTALLED_APPS:

INSTALLED_APPS += ("djcelery", )
CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"

then add the following lines to your settings.py:

import djcelery
djcelery.setup_loader()

USAGE

On linux you can run worker with celery-beat like this:

python manage.py celeryd worker --loglevel=DEBUG  -E -B -c 1
python manage.py help celeryd #to find out the args meaning

Also you will like to monitor tasks in django admin. To enable monitoring fiture you'll need to run celerycam:

python /var/www/gorod/manage.py celerycam

To make periodic task you can use celery.decorators.periodic_task.

# myapp/tasks.py
import datetime
import celery

@celery.decorators.periodic_task(run_every=datetime.timedelta(minutes=5))
def myfunc():
    print 'periodic_task'

Or use

# settings.py
CELERYBEAT_SCHEDULE = {
    'add-every-30-seconds': {
        'task': 'tasks.add',
        'schedule': timedelta(seconds=30),
        'args': (16, 16)
    },
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!