Django的app中使用Celery的Crontab定时执行任务

环境:django 1.6.5 celery 3.1.11 python 2.7

目录结构如下:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值