一、安装方法
# 安装celery 框架 实现分页式任务高度
pip install celery
# 使python与redis 数据库实现连接,若在linux可能要单独下载安装,低版本的redis不兼容celery
pip install redis
# 基于celery基础上封装的分页式任务功能,主要适用于django
pip install django-celery-results
# 基于celery基础上封装的定时任务功能, 主要用于djano
pip install djanto-celery-beat
# python的协程并发库,这是celery实现分页式的并发模式之一
pip install eventlet
二、目录
创建一个django项目(项目名:celery4)和app(app名:app)
.
├── app # app
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── celery4 # 项目
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── templates
三、配置celery
- 在项目下(celery4目录下,和settings.py同级)新建celery.py
celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery4.settings') # 项目名.settings
app = Celery('celery4') # 项目名
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
- 配置定时任务
settings.py
from celery.schedules import crontab
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/11' # redis作为中间件
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/12' # 数据结果存储地址
from datetime import timedelta
CELERY_BEAT_SCHEDULE = {
'celery4_text': { # 任务名(随意起)
'task': 'app.tasks.text', # 定时任务函数路径
'schedule': timedelta(seconds=30), # 任务循环时间
"args": (4,9), # 参数
},
- 在app下新建tasks.py文件(一定要是tasks.py)
from celery import shared_task
from app.models import xxx # 数据库,方便显示
from datetime import datetime
def write_celery_to_record(tips):
"""更新文件"""
project_path = os.path.dirname(os.path.abspath(__file__))
file_path = project_path + r'\celery.txt'
now = datatime.now().strftime("%H:%M:%S")
with open(file_path, "a") as f:
f.write(tips + ',时间:' + now)
f.write("\n")
f.close()
@shared_task
def text(a,b):
write_celery_to_record('执行任务')
c = a+b
xxx.objects.create(
name = c,
tim = now
) # 每执行一次,就会生成一条数据
return "我是celery4.3"
参考:
https://blog.youkuaiyun.com/Coxhuang/article/details/86921407
https://blog.youkuaiyun.com/Coxhuang/article/details/89763076
https://blog.youkuaiyun.com/Coxhuang/article/details/89058429