django-celery定时任务

配置setting

celery 任务队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
setting.py
CELERY_IMPORTS = ('celery_tasks.ansible_setup',)
BROKER_URL = 'redis://127.0.0.1:6379/4'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/4'
CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml']
CELERY_TASK_RESULT_EXPIRES = 60 * 60 * 24 * 30
CELERY_MAX_TASKS_PER_CHILD = 100 # 每个worker最多执行100个任务就会被销毁,可防止内存泄露
CELERY_TASK_TIME_LIMIT = 60 * 10 # 单个任务的运行时间不超过此值,否则会被SIGKILL 信号杀死
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' # 定时任务调度器
djcelery.setup_loader()
from datetime import timedelta
# 定时任务
CELERYBEAT_SCHEDULE = {
'add-every-3-seconds': {
'task': 'celery_tasks.ansible_setup.test_work',
# 'schedule': crontab(minute=u'40', hour=u'17',),
'schedule': timedelta(seconds=3),
'args': (10, 20)
},
}

创建定时任务

1
2
3
4
5
6
7
ansible_setup.py
@task
def test_work(a, b):
c = a * b
logging.info(c)
return True

启动

生成数据库表

1
2
python manage.py makemigrations
python manage.py migrate

启动celery

1
2
python manage.py celery worker -c 4 -l info
python manage.py celery beat -l info

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器