简介并安装

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

下载安装huey。

$ pip install huey

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

$ pip install redis

利用huey定义并执行一些任务时,可以分成这几个文件。
- config.py: 定义使用huey的一些配置,任务的redis存储。

The first step is to configure your queue. The consumer needs to be pointed at a Huey
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,用来存储和取出消息。

from huey import RedisHueyhuey = RedisHuey('base_app', host='127.0.0.1')

或者

from huey import RedisHuey
from redis import ConnectionPoolimport settingsredis_pool = ConnectionPool(host=settings.REDIS_ADDRESS, port=settings.REDIS_PORT, db=0)huey = RedisHuey('base_app', connection_pool=redis_pool)
task.py

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

from base.base_huey import huey@huey.task()
def count_beans(num):print('-- counted %s beans --' % num)for n in range(num):print(n)return '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计划任务相关)。

    def get_option_parser(self):parser = optparse.OptionParser('Usage: %prog [options] ''path.to.huey_instance')def add_group(name, description, options):group = parser.add_option_group(name, description)for abbrev, name, kwargs in options:group.add_option(abbrev, name, **kwargs)add_group('Logging', 'The following options pertain to logging.',self.get_logging_options())add_group('Workers', ('By default huey uses a single worker thread. To specify a ''different number of workers, or a different execution model (such'' as multiple processes or greenlets), use the options below.'),self.get_worker_options())add_group('Scheduler', ('By default Huey will run the scheduler once every second to check'' for tasks scheduled in the future, or tasks set to run at ''specfic intervals (periodic tasks). Use the options below to ''configure the scheduler or to disable periodic task scheduling.'),self.get_scheduler_options())return parser

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

huey_main.py

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

from tasks.huey_task import count_beans# base test
def test_1():count_beans(10)  # no blockcount_beans.schedule(args=(5, ), delay=5)  # delay 5sres = count_beans.schedule(args=(5, ), delay=5)# res.get(blocking=True)res(blocking=True)  # blockif __name__ == '__main__':test_1()print('end')
执行脚本
  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中。

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)

To run these scripts, follow these steps:
1. Ensure you have Redis running locally
2. Ensure you have installed huey
3. Start the consumer: huey_consumer.py main.huey
(notice this is “main.huey” and not “config.huey”).
4. Run the main program: python main.py


huey task简单api介绍

利用@huey.task()能来定义一些基本异步任务,当然还有其他延时任务,周期性任务等。
1. 延时执行:下例展示了两种延时执行的方法:第一种时直接执行延时时间n秒并传入参数;第二种是指定了eta参数,即estimated time of arrival,传入未来的某个时间点,使其在计划时间点执行。

import datetimefrom tasks.huey_task import count_beanscount_beans(3)  # normalcount_beans.schedule(args=(3, ), delay=5)  # delay 5sin_a_minute = datetime.datetime.now() + datetime.timedelta(seconds=60)count_beans.schedule(args=(100,), eta=in_a_minute)

2.阻塞:利用block参数能够使其阻塞。

  res = count_beans(100)# res.get(blocking=True)res(blocking=True)  # block

3.异常重试:当任务出现异常时进行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')

4.周期性任务:利用@huey.periodic_task()来定义一个周期性任务。

  from base.base_huey import hueyfrom huey import crontab@huey.periodic_task(crontab(minute='*'))def print_time():print(datetime.now())

5.取消或暂停任务:revoke。


尝试简单阅读源码

python huey 轻量级异步任务队列简介相关推荐

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

    简介并安装 huey, a little task queue. 轻量级异步任务队列. 下载安装huey. $ pip install huey 下载安装redis依赖(huey暂时只支持redis) ...

  2. python huey 轻量级消息队列

    一huey 库简介 一个轻型的任务队列,功能和相关的broker没有celery强大,重在轻型,而且代码读起来也比较的简单. 1.下载安装huey. pip install huey 2 .下载安装r ...

  3. 【Python】轻量级分布式任务调度系统-RQ

    一 前言       Redis Queue 一款轻量级的P分布式异步任务队列,基于Redis作为broker,将任务存到redis里面,然后在后台执行指定的Job.就目前而言有三套成熟的工具cele ...

  4. python消息队列celery_【干货分享】NTI任务管理之django+python篇celery异步任务使用...

    阅读: 3,538 新浪微博的新鲜事推送如何实现?大规模的服务器如何实现Crontab管理?里面的秘密就在于消息队列.Celery是一个使用Python开发的分布式任务调度模块,是一个简单.灵活.可靠 ...

  5. python任务队列 http_基于Python开发的分布式任务队列:Celery

    Celery (芹菜)是基于Python开发的分布式任务队列.它支持使用任务队列的方式在分布的机器/进程/线程上执行任务调度. 架构设计. Celery的架构由三部分组成,消息中间件(message ...

  6. Py之pyglet:Python之pyglet库的简介、安装、使用详细攻略

    Py之pyglet:Python之pyglet库的简介.安装.使用详细攻略 目录 pyglet库的简介 pyglet库的安装 pyglet库的使用方法 pyglet库的简介 pyglet是一个pyth ...

  7. machinery入门看这一篇(异步任务队列)

    转载地址:machinery入门看这一篇(异步任务队列) 前言 哈喽,大家好,我是asong,这次给大家介绍一个go的异步任务框架machinery.使用过python的同学们都知道Celery框架, ...

  8. Asp-Net-Core开发笔记:集成Hangfire实现异步任务队列和定时任务

    1前言 最近把Python写的数据采集平台往.Net Core上迁移,原本的采集任务使用多进程+线程池的方式来加快采集速度,使用Celery作为异步任务队列兼具定时任务功能,这套东西用着还行,但反正就 ...

  9. db2top详细使用方法_Py之PIL:Python的PIL库的简介、安装、使用方法详细攻略

    Py之PIL:Python的PIL库的简介.安装.使用方法详细攻略 目录 PIL库的简介 PIL库的安装 PIL库的用方法 1.几何图形的绘制与文字的绘制 2.绘制图形的各种案例 PIL库的简介 PI ...

最新文章

  1. EIGRP的等价负载均衡
  2. 关于Linux发行版本RedHat9中文输入法使用问题的说明
  3. 威廉与玛丽学院读计算机博士,威廉与玛丽学院计算机科学(计算运算研究)理学硕士研究生申请要求及申请材料要求清单...
  4. 阿里云服务器CentOS7版本yum方式安装mysql
  5. mysql mydumper_采用mydumper对MySQL部分数据库进行热备
  6. C# 与 Unity 同名函数
  7. 逻辑备库之ORA-01403解决方法
  8. 详解 二叉搜索树-----AVL树
  9. 这个免费的交互式课程在一小时内学习JavaScript
  10. O-C相关-08-动态类型与静态类型
  11. ASP.NET教程11
  12. 220v转5v阻容降压电路
  13. SpringBoot 集成ElasticSearch(二)分页查询
  14. BEA weblogic
  15. Java通过反射获取类的私有属性和方法
  16. 基于STM32的DS1302时钟模块驱动程序
  17. 【190111】VC+Access工程信息管理系统源代码
  18. 软件比较 - Sniffer、Omnipeek、科来网络分析系统过滤器比较之位过滤 在捕获数据包时,有时候需要对一个字节中的某一个位进行精确匹配,这时,我们就需要用到位过滤。位过滤相对于地址、端口、协
  19. linux如何生成awr报告,手工生成AWR报告方法记录
  20. 前端构建和模块化工具-coolie

热门文章

  1. 用计算机做计时时钟的控制,使用Visual C ++制作一个微秒精度的计时器(Vb也适用)...
  2. [行人重识别论文阅读]AlignedReID: Surpassing Human-Level Performance in Person Re-Identification
  3. scss导出颜色变量为空对象
  4. 习题11-1 网页跳转 uva821
  5. 给研华, 控创, 西门子, 凌华, 研祥, 艾迅, 盛博, 诺达佳, 阿普奇 ,桦汉工控机外扩一路,二路CAN,四路等CAN通讯
  6. python制作表格处理_使用python处理excel表格——pandas(1)
  7. 生鲜电商社区团购系统小程序的主要功能
  8. 分布式Id自增生成器
  9. Arduino--读取四块G-302(BH1750FVI)的光照强度
  10. SAP CSO1创建BOM