目录结构如下:
djproj
├── apps
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── app1
│ │ ├── __init__.py
│ │ ├── admin.py
│ │ ├── models.py
│ │ ├── tasks.py
│ │ ├── tests.py
│ │ └── views.py
│ └── app2
│ ├── __init__.py
│ ├── admin.py
│ ├── models.py
│ ├── mytasks.py
│ ├── tests.py
│ └── views.py
├── djproj
│ ├── __init__.py
│ ├── celery.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── files
├── manage.py
└── run.sh
Django中配置Celery参照文档
定时任务配置参照文档:
from celery.schedules import crontab
CELERYBEAT_SCHEDULE = {
# Executes every Monday morning at 7:30 A.M
'add-every-monday-morning': {
'task': 'tasks.add',
'schedule': crontab(hour=7, minute=30, day_of_week=1),
'args': (16, 16),
},
}
要使celery找到相应的tasks有四种方法
1 在项目的celery中写tasks。如在djproj/djproj/celery.py中直接定义task
2 使用autodiscover 但是tasks必须定义在app目录下的名字为tasks.py的文件中,如:apps/app1/tasks.py 否则找不到 ,会报KeyError错误。
3 如果不使用autodiscover,可以在项目的celery中 import 相应的module,相当于在项目的celery中写了相应的task,如在celery.py中 import apps.app2.mytasks
4 在settings.py中设置CELERY_IMPORTS = ('apps.app2.mytasks',) 写到module级
参考:
http://celery.readthedocs.org/en/latest/userguide/tasks.html
http://celery.readthedocs.org/en/latest/getting-started/next-steps.html
http://celery.readthedocs.org/en/latest/django/first-steps-with-django.html#using-celery-with-django
http://celery.readthedocs.org/en/latest/userguide/periodic-tasks.html