python 分布式队列_〖Python〗-- Celery分布式任务队列

【Celery分布式任务队列】

一、Celery介绍和基本使用

Celery 是一个 基于python开发的分布式异步消息任务队列,通过它可以轻松的实现任务的异步处理, 如果你的业务场景中需要用到异步任务,就可以考虑使用celery, 举几个实例场景中可用的例子:

你想对100台机器执行一条批量命令,可能会花很长时间 ,但你不想让你的程序等着结果返回,而是给你返回 一个任务ID,你过一段时间只需要拿着这个任务id就可以拿到任务执行结果, 在任务执行ing进行时,你可以继续做其它的事情。

你想做一个定时任务,比如每天检测一下你们所有客户的资料,如果发现今天 是客户的生日,就给他发个短信祝福

Celery 在执行任务时需要通过一个消息中间件来接收和发送任务消息,以及存储任务结果, 一般使用rabbitMQ or Redis

1.1 Celery有以下优点:

简单:一单熟悉了celery的工作流程后,配置和使用还是比较简单的

高可用:当任务执行失败或执行过程中发生连接中断,celery 会自动尝试重新执行任务

快速:一个单进程的celery每分钟可处理上百万个任务

灵活: 几乎celery的各个组件都可以被扩展及自定制

Celery基本工作流程图

1.2 Celery安装使用

Celery的默认broker是RabbitMQ, 仅需配置一行就可以

使用Redis做broker也可以

安装redis组件

$ pip3 install -U "celery[redis]"

配置

Configuration is easy, just configure the location of your Redis database:

app.conf.broker_url = 'redis://localhost:6379/0'

Where the URL is in the format of:

redis://:password@hostname:port/db_number

all fields after the scheme are optional, and will default to localhost on port 6379, using database 0.

如果想获取每个任务的执行结果,还需要配置一下把任务结果存在哪

If you also want to store the state and return values of tasks in Redis, you should configure these settings:

app.conf.result_backend = 'redis://localhost:6379/0'

1. 3 开始使用Celery

安装celery模块

pip3 install celery

创建一个celery application 用来定义你的任务列表

创建一个任务文件就叫tasks.py

from celery import Celery

app = Celery('tasks',

broker='redis://localhost',

#有用户名密码的话,broker="redis://:mima@127.0.0.1"

backend='redis://localhost')

@app.task

def add(x,y):

print("running...",x,y)

return x+y

启动Celery Worker来开始监听并执行任务

$ celery -A tasks worker --loglevel=info

调用任务

再打开一个终端, 进行命令行模式,调用任务

>>> from tasks import add

>>> add.delay(4, 4)

看你的worker终端会显示收到 一个任务,此时你想看任务结果的话,需要在调用 任务时 赋值个变量

The ready() method returns whether the task has finished processing or not:

>>> result.ready()

False

You can wait for the result to complete, but this is rarely used since it turns the asynchronous call into a synchronous one:

>>> result.get(timeout=1)

8

In case the task raised an exception, get() will re-raise the exception, but you can override this by specifying the propagate argument:

>>> result.get(propagate=False)

If the task raised an exception you can also gain access to the original traceback:

>>> result.traceback

在项目中使用celery

可以把celery配置成一个应用

目录格式如下

proj/__init__.py

/celery.py

/tasks.py

proj/celery.py内容

from __future__ import absolute_import, unicode_literals

from celery import Celery

app = Celery('proj',

broker='amqp://',

backend='amqp://',

include=['proj.tasks'])

# Optional configuration, see the application user guide.

app.conf.update(

result_expires=3600,

)

if __name__ == '__main__':

app.start()

proj/tasks.py中的内容

from __future__ import absolute_import, unicode_literals

from .celery import app

@app.task

def add(x, y):

return x + y

@app.task

def mul(x, y):

return x * y

@app.task

def xsum(numbers):

return sum(numbers)

启动worker

$ celery -A proj worker -l info

输出

-------------- celery@Zhangwei-MacBook-Pro.local v4.0.2 (latentcall)

---- **** -----

--- * *** * -- Darwin-15.6.0-x86_64-i386-64bit 2017-01-26 21:50:24

-- * - **** ---

- ** ---------- [config]

- ** ---------- .> app: proj:0x103a020f0

- ** ---------- .> transport: redis://localhost:6379//

- ** ---------- .> results: redis://localhost/

- *** --- * --- .> concurrency: 8 (prefork)

-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)

--- ***** -----

-------------- [queues]

.> celery exchange=celery(direct) key=celery

后台启动worker

In the background

In production you’ll want to run the worker in the background, this is described in detail in the daemonization tutorial.

The daemonization scripts uses the celery multi command to start one or more workers in the background:

$ celery multi start w1 -A proj -l info

celery multi v4.0.0 (latentcall)

> Starting nodes...

> w1.halcyon.local: OK

You can restart it too:

$ celery multi restart w1 -A proj -l info

celery multi v4.0.0 (latentcall)

> Stopping nodes...

> w1.halcyon.local: TERM -> 64024

> Waiting for 1 node.....

> w1.halcyon.local: OK

> Restarting node w1.halcyon.local: OK

celery multi v4.0.0 (latentcall)

> Stopping nodes...

> w1.halcyon.local: TERM -> 64052

or stop it:

$ celery multi stop w1 -A proj -l info

The stop command is asynchronous so it won’t wait for the worker to shutdown. You’ll probably want to use the stopwait command instead, this ensures all currently executing tasks is completed before exiting:

$ celery multi stopwait w1 -A proj -l info

Celery 定时任务

celery支持定时任务,设定好任务的执行时间,celery就会定时自动帮你执行, 这个定时任务模块叫celery beat

写一个脚本 叫periodic_task.py

from celery import Celery

from celery.schedules import crontab

app = Celery()

@app.on_after_configure.connect

def setup_periodic_tasks(sender, **kwargs):

# Calls test('hello') every 10 seconds.

sender.add_periodic_task(10.0, test.s('hello'), name='add every 10')

# Calls test('world') every 30 seconds

sender.add_periodic_task(30.0, test.s('world'), expires=10)

# Executes every Monday morning at 7:30 a.m.

sender.add_periodic_task(

crontab(hour=7, minute=30, day_of_week=1),

test.s('Happy Mondays!'),

)

@app.task

def test(arg):

print(arg)

add_periodic_task 会添加一条定时任务

上面是通过调用函数添加定时任务,也可以像写配置文件 一样的形式添加, 下面是每30s执行的任务

app.conf.beat_schedule = {

'add-every-30-seconds': {

'task': 'tasks.add',

'schedule': 30.0,

'args': (16, 16)

},

}

app.conf.timezone = 'UTC'

任务添加好了,需要让celery单独启动一个进程来定时发起这些任务, 注意, 这里是发起任务,不是执行,这个进程只会不断的去检查你的任务计划, 每发现有任务需要执行了,就发起一个任务调用消息,交给celery worker去执行

启动任务调度器 celery beat

$ celery -A periodic_task beat

输出like below

celery beat v4.0.2 (latentcall) is starting.

__ - ... __ - _

LocalTime -> 2017-02-08 18:39:31

Configuration ->

. broker -> redis://localhost:6379//

. loader -> celery.loaders.app.AppLoader

. scheduler -> celery.beat.PersistentScheduler

. db -> celerybeat-schedule

. logfile -> [stderr]@%WARNING

. maxinterval -> 5.00 minutes (300s)

此时还差一步,就是还需要启动一个worker,负责执行celery beat发起的任务

启动celery worker来执行任务

$ celery -A periodic_task worker

-------------- celery@Alexs-MacBook-Pro.local v4.0.2 (latentcall)

---- **** -----

--- * *** * -- Darwin-15.6.0-x86_64-i386-64bit 2017-02-08 18:42:08

-- * - **** ---

- ** ---------- [config]

- ** ---------- .> app: tasks:0x104d420b8

- ** ---------- .> transport: redis://localhost:6379//

- ** ---------- .> results: redis://localhost/

- *** --- * --- .> concurrency: 8 (prefork)

-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)

--- ***** -----

-------------- [queues]

.> celery exchange=celery(direct) key=celery

好啦,此时观察worker的输出,是不是每隔一小会,就会执行一次定时任务呢!

注意:Beat needs to store the last run times of the tasks in a local database file (named celerybeat-schedule by default), so it needs access to write in the current directory, or alternatively you can specify a custom location for this file:

$ celery -A periodic_task beat -s /home/celery/var/run/celerybeat-schedule

更复杂的定时配置

上面的定时任务比较简单,只是每多少s执行一个任务,但如果你想要每周一三五的早上8点给你发邮件怎么办呢?哈,其实也简单,用crontab功能,跟linux自带的crontab功能是一样的,可以个性化定制任务执行时间

Linux crontab http://www.cnblogs.com/peida/archive/2013/01/08/2850483.html

from celery.schedules import crontab

app.conf.beat_schedule = {

# Executes every Monday morning at 7:30 a.m.

'add-every-monday-morning': {

'task': 'tasks.add',

'schedule': crontab(hour=7, minute=30, day_of_week=1),

'args': (16, 16),

},

}

上面的这条意思是每周1的早上7.30执行tasks.add任务

还有更多定时配置方式如下:

Example

Meaning

crontab()

Execute every minute.

crontab(minute=0, hour=0)

Execute daily at midnight.

crontab(minute=0, hour='*/3')

Execute every three hours: midnight, 3am, 6am, 9am, noon, 3pm, 6pm, 9pm.

crontab(minute=0,hour='0,3,6,9,12,15,18,21')

Same as previous.

crontab(minute='*/15')

Execute every 15 minutes.

crontab(day_of_week='sunday')

Execute every minute (!) at Sundays.

crontab(minute='*',hour='*',day_of_week='sun')

Same as previous.

crontab(minute='*/10',hour='3,17,22',day_of_week='thu,fri')

Execute every ten minutes, but only between 3-4 am, 5-6 pm, and 10-11 pm on Thursdays or Fridays.

crontab(minute=0,hour='*/2,*/3')

Execute every even hour, and every hour divisible by three. This means: at every hour except: 1am, 5am, 7am, 11am, 1pm, 5pm, 7pm, 11pm

crontab(minute=0, hour='*/5')

Execute hour divisible by 5. This means that it is triggered at 3pm, not 5pm (since 3pm equals the 24-hour clock value of “15”, which is divisible by 5).

crontab(minute=0, hour='*/3,8-17')

Execute every hour divisible by 3, and every hour during office hours (8am-5pm).

crontab(0, 0,day_of_month='2')

Execute on the second day of every month.

crontab(0, 0,day_of_month='2-30/3')

Execute on every even numbered day.

crontab(0, 0,day_of_month='1-7,15-21')

Execute on the first and third weeks of the month.

crontab(0, 0,day_of_month='11',month_of_year='5')

Execute on the eleventh of May every year.

crontab(0, 0,month_of_year='*/3')

Execute on the first month of every quarter.

上面能满足你绝大多数定时任务需求了,甚至还能根据潮起潮落来配置定时任务, 具体看 http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#solar-schedules

Celery与django结合

django 可以轻松跟celery结合实现异步任务,只需简单配置即可

If you have a modern Django project layout like:

- proj/

- proj/__init__.py

- proj/settings.py

- proj/urls.py

- manage.py

then the recommended way is to create a new proj/proj/celery.py module that defines the Celery instance:

file: proj/proj/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', 'proj.settings')

app = Celery('proj')

# Using a string here means the worker don'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()

@app.task(bind=True)

def debug_task(self):

print('Request: {0!r}'.format(self.request))

Then you need to import this app in your proj/proj/__init__.py module. This ensures that the app is loaded when Django starts so that the @shared_task decorator (mentioned later) will use it:

proj/proj/__init__.py:

from __future__ import absolute_import, unicode_literals

# 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

__all__ = ['celery_app']

Note that this example project layout is suitable for larger projects, for simple projects you may use a single contained module that defines both the app and tasks, like in the First Steps with Celery tutorial.

Let’s break down what happens in the first module, first we import absolute imports from the future, so that our celery.py module won’t clash with the library:

from __future__ import absolute_import

Then we set the default DJANGO_SETTINGS_MODULE environment variable for the celery command-line program:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')

You don’t need this line, but it saves you from always passing in the settings module to the celery program. It must always come before creating the app instances, as is what we do next:

app = Celery('proj')

This is our instance of the library.

We also add the Django settings module as a configuration source for Celery. This means that you don’t have to use multiple configuration files, and instead configure Celery directly from the Django settings; but you can also separate them if wanted.

The uppercase name-space means that all Celery configuration options must be specified in uppercase instead of lowercase, and start with CELERY_, so for example the task_always_eager` setting becomes CELERY_TASK_ALWAYS_EAGER, and the broker_url setting becomes CELERY_BROKER_URL.

You can pass the object directly here, but using a string is better since then the worker doesn’t have to serialize the object.

app.config_from_object('django.conf:settings', namespace='CELERY')

Next, a common practice for reusable apps is to define all tasks in a separate tasks.pymodule, and Celery does have a way to  auto-discover these modules:

app.autodiscover_tasks()

With the line above Celery will automatically discover tasks from all of your installed apps, following the tasks.py convention:

Finally, the debug_task example is a task that dumps its own request information. This is using the new bind=True task option introduced in Celery 3.1 to easily refer to the current task instance.

然后在具体的app里的tasks.py里写你的任务

# Create your tasks here

from __future__ import absolute_import, unicode_literals

from celery import shared_task

@shared_task

def add(x, y):

return x + y

@shared_task

def mul(x, y):

return x * y

@shared_task

def xsum(numbers):

return sum(numbers)

在你的django views里调用celery task

from django.shortcuts import render,HttpResponse

# Create your views here.

from bernard import tasks

def task_test(request):

res = tasks.add.delay(228,24)

print("start running task")

print("async task res",res.get() )

return HttpResponse('res %s'%res.get())

在django中使用计划任务功能

There’s  the django-celery-beat extension that stores the schedule in the Django database, and presents a convenient admin interface to manage periodic tasks at runtime.

To install and use this extension:

Use pip to install the package:

$ pip install django-celery-beat

Add the django_celery_beat module to INSTALLED_APPS in your Django project’ settings.py:

INSTALLED_APPS = (

...,

'django_celery_beat',

)

Note that there is no dash in the module name, only underscores.

Apply Django database migrations so that the necessary tables are created:

$ python manage.py migrate

Start the celery beat service using the django scheduler:

$ celery -A proj beat -l info -S django

Visit the Django-Admin interface to set up some periodic tasks.

在admin页面里,有3张表

配置完长这样

此时启动你的celery beat 和worker,会发现每隔2分钟,beat会发起一个任务消息让worker执行scp_task任务

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/332047.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

最大子序列和问题的解(共4种,层层推进)

【0】README 0.1) source code and text description are from data structure and alg analysis ; 0.2) there are 4 methods solving maximum sum of subsequence, but the fourth proves to be the best one , the 3rd deser…

java设计模式代理模式_Java中的代理设计模式

java设计模式代理模式代理对象或代理对象为另一个对象提供占位符,以控制对该对象的访问。 代理充当原始对象的轻量级版本或简化版本。 它支持与原始对象相同的操作,但可以将那些请求委托给原始对象以实现它们。 代理设计模式是一种结构模式,…

Struts2参数值自动注入到JavaBean对象的属性中和JavaBean对象的属性值展示在页面中

文章目录参数值自动注入示例代码将JavaBean的属性值显示在页面上示例代码参数值自动注入 注意事项: 1.前端界面的表单项的参数命名格式为:Action属性名.JavaBean的属性名 2.Action的属性必须要有setter/getter方法,注入时会调用setter方法 …

ibmmq 通道命令_IBM MQ常用命令

常用命令创建队列管理器crtmqm –q QMgrName-q是指创建缺省的队列管理器删除队列管理器dltmqm QmgrName启动队列管理器strmqm QmgrName如果是启动默认的队列管理器,可以不带其名字停止队列管理器endmqm QmgrName 受控停止endmqm –i QmgrName 立即停止endmqm –p Qm…

算法运行时间中的对数

【0】README 0.1) source code and text description are from data structure and alg analysis ; 【1】分析算法最混乱的方面大概集中在对数上面, 除分治算法外,可将对数最常出现的规律概括为下列一般法则: 1.1&a…

java项目:永和大王项目_Java项目:书评

java项目:永和大王项目本文是关于这本书的 Peter Verhas撰写的Java Projects Second Edition 我去年写的 这样一篇文章的目的通常是为了促进这本书的销售。 在这种情况下没有什么不同,但是由于这是我写的书,而且我是撰写评论的人,因此赞美这…

Struts2+Hibernate项目中的时间和日期问题

文章目录数据表中的 datetime 的数据如何通过 json 传送给前端仅展示其日期,而不展示时间日期控件日期时间数据展示问题日期时间数据存储问题场景一场景二场景三场景四数据表中的 datetime 的数据如何通过 json 传送给前端仅展示其日期,而不展示时间 数…

把一个人的特点写具体作文_把一个人的特点写具体作文

把一个人的特点写具体作文在日常学习、工作抑或是生活中,大家都跟作文打过交道吧,写作文可以锻炼我们的独处习惯,让自己的心静下来,思考自己未来的方向。那要怎么写好作文呢?下面是小编为大家整理的把一个人的特点写具…

spring boot简介_Spring Boot简介

spring boot简介在本教程中,我们将看一下Spring Boot,看看它与Spring框架有何不同。 我们还将讨论Spring Boot提供的各种功能。 什么是Spring Boot? 在开发企业级应用程序时,Spring是一个功能强大的框架。 它为我们提供了诸如依赖…

C语言的运算符的优先级与结合性+ASCII表

【0】README 0.1) 内容来源于 C程序设计语言, 旨在整理出C语言的运算符的优先级与结合性, 如下图所示(哥子 记了大半年都没有记住,也是醉了,每次都要去翻); 0.2) 再补充…

退货退款的售后,如何返还金币/有偿优惠券的问题

假设买家购买了3个商品,商品的销售价是10元,商品总金额是30元 买家应付金额是 30 元,买家使用5个金币抵扣5元,买家实付金额是 25 元。 后来买家退货 2 件,怎么退款和退币呢? 要将金币分摊到每个商品上&a…

python orm框架sqlalchemy_python ORM框架:SqlAlchemy

ORM,对象关系映射,即Object Relational Mapping的简称,通过ORM框架将编程语言中的对象模型与数据库的关系模型建立映射关系,这样做的目的:简化sql语言操作数据库的繁琐过程(原生sql的编写及拼接等),转而直接使用对象模…

javadoc提取工具_使JavaDoc保持最新状态的工具

javadoc提取工具在许多项目中,文档不是最新的。 更改代码后,很容易忘记更改文档。 原因是可以理解的。 在代码中进行更改,然后进行调试,然后希望在测试中进行更改(或者,如果您使用的是更多TDD,则…

栈应用(中缀表达式转后缀表达式并计算后缀表达式的值)

【0】README 0.1) 本文旨在总结 中缀表达式转后缀表达式并计算后缀表达式的值 的步骤,并给出源代码实现; 0.2) 本文中涉及到的源代码均为原创,是对中缀转后缀和计算后缀的简单实现,(旨在理清它…

用户/账户/账号的理解

文章目录用户账户账号关系用户 用户概念的理解: 用户就是使用者,可以是个人用户,也可以是机构用户。 账户 账户概念的理解: 账户,所谓“账”,就是系统根据“账”来存储和管理数据,类似记账…

azure 部署java_jClarity:在Azure上升级到Java

azure 部署java在互联世界公共基础设施的新时代,最大和最重要的两个方面是Java和OpenJDK的诞生和兴起。 因此,许多公司将时间和资源投入到构建最先进的技术上,以确保整个行业在未来几年内在AdoptOpenJDK上拥有丰富的质量,而且免费…

黑苹果sd卡认不出来_天生一对:新入苹果M1笔记本,DOCKCASE拓展坞弥补缺憾

2010年刚上大学那会,入手了人生第一台笔记本电脑,两边密密麻麻的各种接口,也没感觉到接口多少的价值;2016年年中入手了人生第一台苹果笔记本,第一次觉得电脑接口不够用;如今四年过去了电脑也到了更新换代的…

利用树的先序和后序遍历打印os中的目录树

【0】README0.1)本代码均为原创,旨在将树的遍历应用一下下以加深印象而已;(回答了学习树的遍历到底有什么用的问题?)你对比下linux 中的文件树 和我的打印结果就明理了;0.2)我们采用…

Hibernate常用API

文章目录删除指定的记录新增记录更新记录清空缓存将实体对象从缓存中清除将缓存中更新的数据同步到数据库把数据库中的数据刷到缓存中查询多个对象(也就是查询多条记录)查询指定ID的对象(查询指定ID值的记录)参考删除指定的记录 U…

solid设计原则_SOLID设计原则

solid设计原则介绍: Robert C. Martin定义了五项面向对象的设计原则: 小号英格尔-责任原则 笔封闭原则 大号 iskov的替换原则 我覆盖整个院落分离原则,并 d ependency倒置原则 这些一起被普遍称为SOLID原则。 在设计面向对象的系统时&a…