python celery应用场景_python celery介绍和基本使用

08 python celery介绍和基本使用

celery分布式任务队列

RPC远程,当执行一条命令,等待远程执行结果返回客户端。

在Linux上可以在后台执行,不影响其他任务执行。(涉及到异步)

1、分布式任务运算celery

Crontab操作系统本身任务计划

Celery也可以实现定时任务,不需要操作系统。

Rabbitmq也可以实现异步。

2、测试代码:

Celery在Windows上执行有问题,在Linux上使用。

[root@backup testcleery]# celery -A celery_test worker -l debug 启动过程中可能需要调整环境变量。export C_FORCE_ROOT=True

[root@backup testcleery]# export C_FORCE_ROOT=True

[root@backup testcleery]# celery -A celery_test worker -l info

查看日志,任务模块加载成功。Celery两个模块都已加载下来。

测试celery模块。

3、测试同时启动2个worker服务。

[root@backup testcleery]# export C_FORCE_ROOT=True

[root@backup testcleery]# celery -A celery_test worker -l info

[root@backup testcleery]# celery -A celery_test worker -l debug

两个worker抢任务,随机分发任务到worker。

多开几个终端进行测试,应用程序会随机选择worker。

4、来个复杂任务,按照生产情况,执行过程很长的服务

[root@backup testcleery]# vim celery_test2.py

[root@backup testcleery]# celery -A celery_test2 worker -l info

root@backup testcleery]# python

>>>from celery_test2 import add,cmd

>>>t1 = cmd.delay('abcedef')

>>> t1.ready()

False

>>> t1.ready()

True

>>>t1.get()

1569491327.817837

>>>

10s任务卡住了。

当t1.ready()变成true,可以取值。

5、在项目中使用。指定项目文件。

[root@backup testcleery]# mkdir pro

[root@backup testcleery]# cd pro/

[root@backup pro]# pwd

/root/testcleery/pro

[root@backup pro]# touch __init__.py

项目目录结构和项目启动方式。

[root@backup pro]#

生产项目编写。

[root@backup testcleery]# vim pro/celery.py

from __future__ import absolute_import, unicode_literals

from celery import Celery  # 默认从Python绝对路径引入celery包

配置认为列表项。

启动celery项目。

[root@backup testcleery]# celery -A pro worker -l debug

[root@backup testcleery]# python

Python 3.6.3 |Anaconda, Inc.| (default, Oct 13 2017, 12:02:49)

[GCC 7.2.0] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> from pro import tasks, tasks2

>>> t1 = tasks2.cmd('df')

running cmd... df

>>> t1=tasks.xsum.delay([1,2,4,3,2])

>>> t1.get()

12

>>>

Celery跟Django结合使用的比较多。后面章节重点讲解。

Celery做定时任务。

后台启动方式,

[root@backup testcleery]# celery multi start w1 -A pro worker -l info  启动

[root@backup testcleery]# celery multi stop w1 -A pro worker -l info  关闭

观察到,一个worker任务有3个进程在跑。

停止任务

celery multi stopwait w1 -A proj -l info

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值