【PYthon分布式】huey:python轻量级异步任务队列简介

简介并安装

huey,a little task queue.
轻量级异步任务队列。

下载安装huey。

下载安装redis依赖(huey暂时只支持redis)。

dis

利用huey定义并执行一些任务时,可以分成这几个文件

  • config.py: 定义使用huey的一些配置,任务的redis存储。

The first step is to configure your queue. The consumer needs to be pointed at a instance,which specifies which backend to use.

  • task.py: 定义你需要执行的一些异步任务。
  • huey_consumer.py: 开启huey consumer的入口(huey提供)。
  • huey_main.py: 执行异步任务。

config.py

实际上就是利用redis创建consumer所指向的huey实例,huey实际上包含了一个队列queue,用来存储和取出消息。

 huey  RedisHuey

huey = RedisHuey(<span class="hljs-string">'base_app',host=<span class="hljs-string">'127.0.0.1')

或者

<code class="language-javascript"><code class="javascript"><span class="hljs-keyword">from huey <span class="hljs-keyword">import RedisHuey
<span class="hljs-keyword">from redis <span class="hljs-keyword">import ConnectionPool

<span class="hljs-keyword">import settings

redis_pool = ConnectionPool(host=settings.REdis_ADDRESS,port=settings.REdis_PORT,db=<span class="hljs-number">0)

huey = RedisHuey(<span class="hljs-string">'base_app',connection_pool=redis_pool)

task.py

利用config.py所创建的huey来修饰普通函数使之成为huey任务。
这样就定义了一个最基本的异步任务。(base_huey.py 及上述的 config.py)

<code class="language-python"><code class="python"><span class="hljs-keyword">from base.base_huey <span class="hljs-keyword">import huey

<span class="hljs-Meta">@huey.task()
<span class="hljs-function"><span class="hljs-keyword">def <span class="hljs-title">count_beans<span class="hljs-params">(num):
print(<span class="hljs-string">'-- counted %s beans --' % num)
<span class="hljs-keyword">for n <span class="hljs-keyword">in range(num):
print(n)
<span class="hljs-keyword">return <span class="hljs-string">'Counted %s beans' % num

huey_consumer.py

之前习惯把huey包里的huey_consumer.py文件直接拿出来到主目录然后执行,新版的的huey_consumer.py与旧版的稍微有点区别。
新版本增加一个consumer_options.py,用来定义封装了一些consumer相关的配置和命令行解析的处理类;在旧版中,这些都是直接定义在huey_consumer.py中。
查看OptionParserHandler源码可知,huey_consumer可以包含很多参数,主要分为三个group(Logging日志记录,Workers任务worker相关,Scheduler计划任务相关)。

<code class="language-ruby"><code class="ruby">    <span class="hljs-function"><span class="hljs-keyword">def <span class="hljs-title">get_option_parser<span class="hljs-params">(<span class="hljs-keyword">self):
parser = optparse.OptionParser(<span class="hljs-string">'Usage: %prog [options] '
<span class="hljs-string">'path.to.huey_instance')

    <span class="hljs-function"&gt;<span class="hljs-keyword"&gt;def</span> <span class="hljs-title"&gt;add_group</span><span class="hljs-p<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>ms"&gt;(name,description,options)</span></span>:
        group = parser.add_option_group(name,description)
        <span class="hljs-keyword"&gt;for</span> abbrev,name,<a href="https://www.jb51.cc/tag/kwargs/" target="_blank" class="keywords">kwargs</a> <span class="hljs-keyword"&gt;in</span> <span class="hljs-symbol"&gt;options:</span>
            group.add_option(abbrev,**<a href="https://www.jb51.cc/tag/kwargs/" target="_blank" class="keywords">kwargs</a>)

    add_group(<span class="hljs-string"&gt;'Logging'</span>,<span class="hljs-string"&gt;'The following options pertain to logging.'</span>,<span class="hljs-keyword"&gt;self</span>.get_logging_options())

    add_group(<span class="hljs-string"&gt;'Workers'</span>,(
        <span class="hljs-string"&gt;'By default huey uses a single worker thread. To specify a '</span>
        <span class="hljs-string"&gt;'different number of workers,or a different execution model (such'</span>
        <span class="hljs-string"&gt;' as multiple processes or <a href="https://www.jb51.cc/tag/greenlets/" target="_blank" class="keywords">greenlets</a>),use the options below.'</span>),<span class="hljs-keyword"&gt;self</span>.get_worker_options())

    add_group(<span class="hljs-string"&gt;'Scheduler'</span>,(
        <span class="hljs-string"&gt;'By default Huey will run the scheduler once every second to check'</span>
        <span class="hljs-string"&gt;' for tasks scheduled in the future,or tasks set to run at '</span>
        <span class="hljs-string"&gt;'specfic intervals (periodic tasks). Use the options below to '</span>
        <span class="hljs-string"&gt;'con<a href="https://www.jb51.cc/tag/fig/" target="_blank" class="keywords">fig</a>ure the scheduler or to <a href="https://www.jb51.cc/tag/dis/" target="_blank" class="keywords">dis</a>able periodic task scheduling.'</span>),<span class="hljs-keyword"&gt;self</span>.get_scheduler_options())

    <span class="hljs-keyword"&gt;return</span> parser

最常用的一些参数:

  • -l 指定huey异步任务执行时的日志文件(也可以通过ConsumerConfigsetup_logger()来定义logger)。
  • -w 执行器worker队列的数量
  • -k worker的类型(process,thread,greenlet,认是thread)
  • -d 轮询队列的最短时间间隔
huey_main.py

定义需要执行huey任务的方法

<code class="language-python"><code class="python"><span class="hljs-keyword">from tasks.huey_task <span class="hljs-keyword">import count_beans

<span class="hljs-comment"># base test
<span class="hljs-function"><span class="hljs-keyword">def <span class="hljs-title">test_1<span class="hljs-params">():
count_beans(<span class="hljs-number">10) <span class="hljs-comment"># no block

count_beans.schedule(args=(<span class="hljs-number"&gt;5</span>,),delay=<span class="hljs-number"&gt;5</span>)  <span class="hljs-comment"&gt;# delay 5s</span>

res = count_beans.schedule(args=(<span class="hljs-number"&gt;5</span>,delay=<span class="hljs-number"&gt;5</span>)
<span class="hljs-comment"&gt;# res.get(blocking=True)</span>
res(blocking=<span class="hljs-keyword"&gt;True</span>)  <span class="hljs-comment"&gt;# block</span>

<span class="hljs-keyword">if name == <span class="hljs-string">'main':

test_1()

print(<span class="hljs-string"&gt;'end'</span>)

执行脚本
  1. 开启consumer轮询:python huey_consumer_new.py tasks.huey_task.huey -l logs/base_huey.log -w 1
    tasks.task.huey即上述的task.py,在此时后缀名需要替换成 .huey。
  2. 执行异步方法pyton huey_main.py

ps:官方文档中是将 huey 实例和task任务都引入到main.py中。

<pre class="hljs undefined">

main.py

from config import huey # import our "huey" object
from tasks import count_beans # import our task
if name == 'main':
beans = raw_input('How many beans? ')
count_beans(int(beans))
print('Enqueued job to count %s beans' % beans)

<code class="language-ruby"><code class="ruby">To run these scripts,follow these <span class="hljs-symbol">steps:
<span class="hljs-number">1. Ensure you have [Redis](<span class="hljs-symbol">http:/<span class="hljs-regexp">/redis.io/) running locally
<span class="hljs-number">2. Ensure you have [installed huey](<span class="hljs-symbol">http:/<span class="hljs-regexp">/huey.readthedocs.io/en<span class="hljs-regexp">/latest/installation.html<span class="hljs-comment">#installation)
<span class="hljs-number">3. Start the <span class="hljs-symbol">consumer: huey_consumer.py main.huey
(notice this is “main.huey” <span class="hljs-keyword">and <span class="hljs-keyword">not “config.huey”).
<span class="hljs-number">4. Run the main <span class="hljs-symbol">program: python main.py


<span class="hljs-comment">#####huey task简单api介绍
利用<span class="hljs-string"></span><span class="hljs-string"&gt;`@huey.task()`</span><span class="hljs-string"&gt;能来定义一些基本异步任务,当然还有其他延时任务,周期性任务等。
<span class="hljs-number">1. 延时执行:下例展示了两种延时执行的方法:第一种时直接执行延时时间n秒并传入参数;第二种是指定了eta参数,即estimated time of arrival,传入未来的某个时间点,使其在计划时间点执行。

import datetime

from tasks.huey_task import count_beans

count_beans(3) # normal

count_beans.schedule(args=(3,delay=5) # delay 5s

in_a_minute = datetime.datetime.Now() + datetime.timedelta(seconds=60)
count_beans.schedule(args=(100,eta=in_a_minute)

<pre class="hljs undefined">2. 阻塞:利用block参数能够使其阻塞。

res = count_beans(100)

res.get(blocking=True)

res(blocking=True) # block

<code class="language-ruby"><code class="ruby"><span class="hljs-number">3. 异常重试:当任务出现异常时进行<span class="hljs-keyword">retry,并且可以指定重试延时时间。

from base.base_huey import huey

retry 3 times delay 5s

@huey.task(retries=3,retry_delay=5)
def try_reties_by_delay():
print('trying %s' % datetime.Now())
raise Exception('try_reties_by_delay')

<code class="language-javascript"><code class="javascript"><span class="hljs-number">4. 周期性任务:利用<span class="hljs-string"></span><span class="hljs-string"&gt;`@huey.periodic_task()`</span><span class="hljs-string"&gt;来定义一个周期性任务。

from base.base_huey import huey
from huey import crontab

@huey.periodic_task(crontab(minute='*'))
def print_time():
print(datetime.Now())

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


我最近重新拾起了计算机视觉,借助Python的opencv还有face_recognition库写了个简单的图像识别demo,额外定制了一些内容,原本想打包成exe然后发给朋友,不过在这当中遇到了许多小问题,都解决了,记录一下踩过的坑。 1、Pyinstaller打包过程当中出现warning,跟d
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Pooling在中文当中的意思是“池化”,在神经网络当中非常常见,通常用的比较多的一种是Max Pooling,具体操作如下图: 结合图像理解,相信你也会大概明白其中的本意。不过Pooling并不是只可以选取2x2的窗口大小,即便是3x3,
记得大一学Python的时候,有一个题目是判断一个数是否是复数。当时觉得比较复杂不好写,就琢磨了一个偷懒的好办法,用异常处理的手段便可以大大程度帮助你简短代码(偷懒)。以下是判断整数和复数的两段小代码: 相信看到这里,你也有所顿悟,能拓展出更多有意思的方法~
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic histogram2. 数据分布与密度信息显示 Control rug and density on seaborn histogram3. 带箱形图的直方图 Histogram with a boxplot on t
文章目录 5 小提琴图Violinplot1. 基础小提琴图绘制 Basic violinplot2. 小提琴图样式自定义 Custom seaborn violinplot3. 小提琴图颜色自定义 Control color of seaborn violinplot4. 分组小提琴图 Group
文章目录 4 核密度图Densityplot1. 基础核密度图绘制 Basic density plot2. 核密度图的区间控制 Control bandwidth of density plot3. 多个变量的核密度图绘制 Density plot of several variables4. 边
首先 import tensorflow as tf tf.argmax(tenso,n)函数会返回tensor中参数指定的维度中的最大值的索引或者向量。当tensor为矩阵返回向量,tensor为向量返回索引号。其中n表示具体参数的维度。 以实际例子为说明: import tensorflow a
seaborn学习笔记章节 seaborn是一个基于matplotlib的Python数据可视化库。seaborn是matplotlib的高级封装,可以绘制有吸引力且信息丰富的统计图形。相对于matplotlib,seaborn语法更简洁,两者关系类似于numpy和pandas之间的关系,seabo
Python ConfigParser教程显示了如何使用ConfigParser在Python中使用配置文件。 文章目录 1 介绍1.1 Python ConfigParser读取文件1.2 Python ConfigParser中的节1.3 Python ConfigParser从字符串中读取数据
1. 处理Excel 电子表格笔记(第12章)(代码下载) 本文主要介绍openpyxl 的2.5.12版处理excel电子表格,原书是2.1.4 版,OpenPyXL 团队会经常发布新版本。不过不用担心,新版本应该在相当长的时间内向后兼容。如果你有新版本,想看看它提供了什么新功能,可以查看Open
1. 发送电子邮件和短信笔记(第16章)(代码下载) 1.1 发送电子邮件 简单邮件传输协议(SMTP)是用于发送电子邮件的协议。SMTP 规定电子邮件应该如何格式化、加密、在邮件服务器之间传递,以及在你点击发送后,计算机要处理的所有其他细节。。但是,你并不需要知道这些技术细节,因为Python 的
文章目录 12 绘图实例(4) Drawing example(4)1. Scatterplot with varying point sizes and hues(relplot)2. Scatterplot with categorical variables(swarmplot)3. Scat
文章目录 10 绘图实例(2) Drawing example(2)1. Grouped violinplots with split violins(violinplot)2. Annotated heatmaps(heatmap)3. Hexbin plot with marginal dist
文章目录 9 绘图实例(1) Drawing example(1)1. Anscombe’s quartet(lmplot)2. Color palette choices(barplot)3. Different cubehelix palettes(kdeplot)4. Distribution
Python装饰器教程展示了如何在Python中使用装饰器基本功能。 文章目录 1 使用教程1.1 Python装饰器简单示例1.2 带@符号的Python装饰器1.3 用参数修饰函数1.4 Python装饰器修改数据1.5 Python多层装饰器1.6 Python装饰器计时示例 2 参考 1 使
1. 用GUI 自动化控制键盘和鼠标第18章 (代码下载) pyautogui模块可以向Windows、OS X 和Linux 发送虚拟按键和鼠标点击。根据使用的操作系统,在安装pyautogui之前,可能需要安装一些其他模块。 Windows: 不需要安装其他模块。OS X: sudo pip3
文章目录 生成文件目录结构多图合并找出文件夹中相似图像 生成文件目录结构 生成文件夹或文件的目录结构,并保存结果。可选是否滤除目录,特定文件以及可以设定最大查找文件结构深度。效果如下: root:[z:/] |--a.py |--image | |--cat1.jpg | |--cat2.jpg |
文章目录 VENN DIAGRAM(维恩图)1. 具有2个分组的基本的维恩图 Venn diagram with 2 groups2. 具有3个组的基本维恩图 Venn diagram with 3 groups3. 自定义维恩图 Custom Venn diagram4. 精致的维恩图 Elabo
mxnet60分钟入门Gluon教程代码下载,适合做过深度学习的人使用。入门教程地址: https://beta.mxnet.io/guide/getting-started/crash-course/index.html mxnet安装方法:pip install mxnet 1 在mxnet中使
文章目录 1 安装2 快速入门2.1 基本用法2.2 输出图像格式2.3 图像style设置2.4 属性2.5 子图和聚类 3 实例4 如何进一步使用python graphviz Graphviz是一款能够自动排版的流程图绘图软件。python graphviz则是graphviz的python实