利用celery+django 在admin后台设置定时任务

本文涉及的产品
云数据库 Redis 版,标准版 2GB
推荐场景:
搭建游戏排行榜
云原生内存数据库 Tair,内存型 2GB
日志服务 SLS,月写入数据量 50GB 1个月
简介:

经常用python开发web应用时,会涉及到定时任务的脚本,以前用linux自带的crontab来操作,但是感觉不太接地气,后来发现用celery+django 可以方便的实现!

安装软件环境如下:

python 2.7.5

Django==1.8.2

celery==3.1.18

celery-with-redis==3.0

django-celery==3.1.16

MySQL-python==1.2.3

supervisor==3.1.3

使用pip方式安装完以上软件,并且默认系统已经安装了redis和mysql服务器!


一 首先创建project:

django-admin.py createproject picha

然后创建名称为demo的app:

django-admin.py startapp demo

项目的目录结构为:

wKiom1agmSST4mpHAAFz4NX9Bg4001.jpg


二 下面在settings文件中配置celery相关的配置:

1
2
3
4
5
6
7
8
9
10
11
# CELERY STUFF
import  djcelery
djcelery.setup_loader()
BROKER_URL =  'redis://localhost:6379'
CELERYBEAT_SCHEDULER =  'djcelery.schedulers.DatabaseScheduler'  # 定时任务
CELERY_RESULT_BACKEND =  'djcelery.backends.database:DatabaseBackend'
CELERY_RESULT_BACKEND =  'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = [ 'application/json' ]
CELERY_TASK_SERIALIZER =  'json'
CELERY_RESULT_SERIALIZER =  'json'
CELERY_TIMEZONE =  'Asia/Shanghai'
1
2
3
4
5
6
7
8
9
10
INSTALLED_APPS = (
     'django.contrib.admin' ,
     'django.contrib.auth' ,
     'django.contrib.contenttypes' ,
     'django.contrib.sessions' ,
     'django.contrib.messages' ,
     'django.contrib.staticfiles' ,
     'demo' ,
     'djcelery' ,
)


在和settings.py同级目录中编辑文件 |__init__.py

1
2
3
4
5
6
7
8
#! /usr/bin/env python
# coding: utf-8
 
from __future__  import  absolute_import
 
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery  import  app as celery_app


然后修改市区:

TIME_ZONE = 'Asia/Shanghai'

 市区不对,计划任务是不会按时间执行的!


另外,我们还需要在创建一个celery.py文件,他会自动发现我们app下面的task!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#! /usr/bin/env python
# coding: utf-8
 
from __future__  import  absolute_import
import  os
from celery  import  Celery
from django.conf  import  settings
 
# set the default Django settings module for the 'celery' program.
os.environ.setdefault( 'DJANGO_SETTINGS_MODULE' 'picha.settings' )
app = Celery( 'picha' )
 
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object( 'django.conf:settings' )
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
 
 
@app.task(bind=True)
def debug_task(self):
     print( 'Request: {0!r}' . format (self.request))


现在我们在demo的app下面创建测试用的task!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from __future__  import  absolute_import
from celery  import  shared_task,task
 
 
@shared_task()
def add(x,y):
     # return x + y
     print x + y
 
@shared_task()
def mul(x,y):
     print  "%d * %d = %d"  %(x,y,x*y)
     return  x*y
 
@shared_task()
def sub(x,y):
     print  "%d - %d = %d" %(x,y,x-y)
     return  x - y
 
@task(ignore_result=True,max_retries=1,default_retry_delay=10)
def just_print():
     print  "Print from celery task"


到这里,django和celery部分已经安装完成!


三 我现在开始配置supervisor,用来启动相关celery程序:

1)初始化supervisor配置文件!

echo_supervisord_conf > /etc/supervisord.conf


2)然后在supervisord.conf文件末尾添加如下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
[program:djangoproject.celeryd]
command = /usr/local/pyenv/shims/python  /usr/local/coding/pythoner/picha/manage .py celeryd --concurrency=1
user=root
numprocs=1
directory= /usr/local/coding/pythoner/picha
stdout_logfile= /var/log/celery_worker .log
stderr_logfile= /var/log/celery_worker .log
autostart= true
autorestart= true
startsecs=10
stopwaitsecs = 120
priority=998
 
[program:djangoproject.celerybeat]
command = /usr/local/pyenv/shims/python  /usr/local/coding/pythoner/picha/manage .py celery beat --schedule= /tmp/celerybeat-schedule  --pidfile= /tmp/django_celerybeat .pid --loglevel=INFO
user=root
numprocs=1
directory= /usr/local/coding/pythoner/picha
stdout_logfile= /var/log/celery_beat .log
stderr_logfile= /var/log/celery_beat .log
autostart= true
autorestart= true
startsecs=10
stopwaitsecs = 120
priority=998
 
[program:djangoproject.celerycam]
command = /usr/local/pyenv/shims/python  /usr/local/coding/pythoner/picha/manage .py celerycam --frequency=10.0
user=root
numprocs=1
directory= /usr/local/coding/pythoner/picha
stdout_logfile= /var/log/celerycam .log
stderr_logfile= /var/log/celerycam .log
autostart= true
autorestart= true
startsecs=10
stopwaitsecs = 120
priority=998


四 现在我们需要把celery相关的库文件同步到mysql中,我们使用命令:

python manage.py syncdb

然后创建superuser

django-admin manage.py createsuperuser


启动supervisor:

supervisord -d

查看服务是否启动成功,使用命令supervisorctl status


djangoproject.celerybeat         RUNNING   pid 3061, uptime 1:03:27

djangoproject.celerycam          RUNNING   pid 3063, uptime 1:03:27

djangoproject.celeryd            RUNNING   pid 3062, uptime 1:03:27




然后我们进入到django-admin后台,

现在我们启动django:

 python manage.py runserver 0.0.0.0:8008


进入后台后,点击“Periodic tasks”:

可以看到写在tasks.py下面的方法,在下拉菜单中都出现了,我们只用选择对应的时间即可!

wKiom1ago13D_WhAAACwT_ocy4s066.png

现在,我们开始选择计划任务的时间:

我们创建一个定时任务,没10s,print一个数值,放在在日志文件中查看:

wKioL1agpDvgqiviAABBus0fwxA090.png

我们查看日志文件:

wKioL1agpH_gHaO1AABQZc6BUb0321.png符合我们在web后台的设置!


我们在设置一个加法运算,每隔15s运行一次,而且我们可以在web平台后端动态的修改所传的参数,

第一次,我们传入参数9和5,结果应该为14,我们看下设置和日志:

wKioL1agpPSSMJ3wAABhrOzHmk0255.png

我再看下日志:

wKioL1agpSPBSEG9AABE04bbRJk013.png


然后我们在web后台修改传入参数为10和7,不重启服务,计算的结果动态变化为17!

wKiom1agpVbyw9hYAAA69d0kMYg405.png

我们发现,结果数据已经动态变化!


我们如果启动了 supervisor脚本中的:/usr/local/coding/pythoner/picha/manage.py celerycam --frequency=10.0

就可以在admin后台查看 woker是不是在线:

wKioL1agpirRGgfvAABHkqS5MS4227.pngcelery-django相关的配置就完成了!


PS:配置过程中计划任务的结果只能日志中查看,不知道怎么在admin的后台中显示,如果大家知道,可以告诉我,3Q!





本文转自 shine_forever 51CTO博客,原文链接:http://blog.51cto.com/shineforever/1737323
相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore     ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库 ECS 实例和一台目标数据库 RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
3月前
|
前端开发 数据库 Python
Django项目之电商购物商城 -- 修改/删除收货地址/设置默认地址
Django项目之电商购物商城 -- 修改/删除收货地址/设置默认地址
|
23天前
|
机器学习/深度学习 数据采集 数据可视化
基于爬虫和机器学习的招聘数据分析与可视化系统,python django框架,前端bootstrap,机器学习有八种带有可视化大屏和后台
本文介绍了一个基于Python Django框架和Bootstrap前端技术,集成了机器学习算法和数据可视化的招聘数据分析与可视化系统,该系统通过爬虫技术获取职位信息,并使用多种机器学习模型进行薪资预测、职位匹配和趋势分析,提供了一个直观的可视化大屏和后台管理系统,以优化招聘策略并提升决策质量。
|
23天前
|
搜索推荐 前端开发 数据可视化
【优秀python web毕设案例】基于协同过滤算法的酒店推荐系统,django框架+bootstrap前端+echarts可视化,有后台有爬虫
本文介绍了一个基于Django框架、协同过滤算法、ECharts数据可视化以及Bootstrap前端技术的酒店推荐系统,该系统通过用户行为分析和推荐算法优化,提供个性化的酒店推荐和直观的数据展示,以提升用户体验。
|
5天前
|
消息中间件 存储 监控
Django后端架构开发:Celery异步调优,任务队列和调度
Django后端架构开发:Celery异步调优,任务队列和调度
17 1
|
24天前
|
机器学习/深度学习 前端开发 数据挖掘
基于Python Django的房价数据分析平台,包括大屏和后台数据管理,有线性、向量机、梯度提升树、bp神经网络等模型
本文介绍了一个基于Python Django框架开发的房价数据分析平台,该平台集成了多种机器学习模型,包括线性回归、SVM、GBDT和BP神经网络,用于房价预测和市场分析,同时提供了前端大屏展示和后台数据管理功能。
|
19天前
|
调度 Python
在 Django 上实现定时任务的指南
在 Django 中实现定时任务有多种方法,包括使用 Celery 和 Celery Beat、django-background-tasks、以及 APScheduler。根据您的需求和应用场景,可以选择最适合的方案。每种方法都有其优缺点,选择时应考虑任务复杂性、系统资源、以及维护成本。通过这些工具,您可以有效地管理和调度后台任务,提高应用程序的自动化水平和运行效率。
|
24天前
|
数据采集 数据可视化 数据挖掘
基于Django的数据分析可视化系统,有后台,有增删改查,实现多用户登录
本文介绍了一个基于Django框架开发的今日头条数据分析可视化系统,该系统具备后台管理、增删改查功能以及多用户登录,利用数据可视化技术为新闻媒体行业提供数据管理和决策支持。
基于Django的数据分析可视化系统,有后台,有增删改查,实现多用户登录
|
25天前
|
前端开发 关系型数据库 MySQL
Python基于Django框架图书管理系统,Bootstrap框架UI,后台EasyUI框架UI,有登录,实现增删改查的富文本效果
本文介绍了一个使用Python Django框架开发的图书管理系统,该系统采用Bootstrap框架进行前端UI设计,EasyUI框架用于后台UI界面,集成了富文本编辑器,并实现了登录及增删改查功能。
|
5天前
|
消息中间件 NoSQL 调度
Django后端架构开发:Django 与 Celery 的深度集成
Django后端架构开发:Django 与 Celery 的深度集成
40 0
|
2月前
|
Linux 调度 数据库
Django使用django-apscheduler实现定时任务
【7月更文挑战第8天】定时任务可以在后台定时执行指定的代码,避免了很多人为操作。下面是在Django项目中如何使用定时任务的具体操作流程
164 1