1,定时任务环境
django-1.9.8
celery-4.2.1
django-celery 3.2.2
django-celery-beat 1.1.1
eventlet (win10环境必须要安装的)
安装方式 pip install django 不一一举例。
2,配置settings.py文件
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_celery_beat' #添加app
]
#配置APP后要迁移数据 makemigrations
#指定Redis数据库为消息队列,接受任务生产者发送过来的任务消息, 存进队列再按序分发给任务消费方
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Shanghai'
# CELERY_IMPORTS = ("tasks",)
from datetime import timedelta
#定时任务
CELERY_BEAT_SCHEDULE = {
'add-every-30-seconds': {
'task': 'epgapp.tasks.add', #任务名
'schedule': timedelta(seconds=1), #每一秒执行一次该任务
'args': (2,2) #参数
},
'add-every-10-seconds': {
'task': 'epgapp.tasks.mul',
'schedule': timedelta(seconds=5),
'args': (10, 10)
},
'add-every-3-seconds': {
'task': 'epgapp.tasks.SS',
'schedule': timedelta(seconds=2),
'args': ()
},
}
3,定时任务 /epgapp/tasks.py
from __future__ import absolute_import,unicode_literals
from celery import shared_task
import time
from .models import Epg
a = 10
@shared_task
def add(x,y):
print(time.time())
return 1
@shared_task
def mul(x,y):
return x*y
@shared_task
def xsum(num):
print(num)
4,启动定时任务
celery -A bokong2 beat -l info
#在新窗口打开运行worker
celery -A bokong2 worker -P eventlet
网友评论