【Python】:拓展Queue实现有序不重复队列
最近手头有个需求是这样的,定期检查数据库获取失败任务并且进行重启。最早想到的是添加一个生产者&&消费者队列,但是发现很多棘手的问题。
1.重启任务是调用的一个shell脚本然后在脚本中又调用python程序,所以任务完成的状态回传略纠结。
2.重启任务有多种重启方式,要根据任务的不同FailStat来判断重启方式,这样的话队列中不仅要有任务名称,还需要状态码
3.Python里的原生Queue不会进行去重,可能会导致队列中对失败任务无论重启成功与否会进行多次重跑。
在StackOverflow上看了一些文章,都是推荐拓展Queue,看了看Queue.Queue的源代码,发现果然很适合拓展:
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held # Initialize the queue representation
def _init(self, maxsize):
self.queue = deque() def _qsize(self, len=len):
return len(self.queue) # Put a new item in the queue
def _put(self, item):
self.queue.append(item) # Get an item from the queue
def _get(self):
return self.queue.popleft()
So,自己通过字典来实现了一个类似链表的类,然后继承Queue.Queue并重写方法,实现了一个新的有序不重复队列:
#!/usr/bin/env python
# Filename:ordered_map_queue.py
# -*- encoding:utf-8 -*-
import sys
import Queue class Link():
''' No repeat link '''
def __init__(self):
self.map = {}
self.tail = "head"
self.map["head"] = {"stat":0, "next":"null"} def __contains__(self,key):
return key in self.map def __len__(self):
return len(self.map)-1 def isEmpty(self):
if self.getHead() == "null":
return True
else:
return False def clearLink(self):
self.map.clear() def getTail(self):
return self.tail def getHead(self):
return self.map["head"]["next"] def add(self, string):
# self.test_output("OrderedMapQueue")
args = string.split('\t')
item = args[0]
stat = args[1]
if item not in self.map:
self.map[item] = {"stat":stat, "next":"null"}
self.map[self.tail]["next"] = item
self.tail = item def pop(self):
if not self.isEmpty():
head_task = self.map["head"]["next"]
rt_value = "%s\t%s" % (head_task, self.map[head_task]["stat"])
self.map["head"]["next"] = self.map[head_task]["next"]
del self.map[head_task]
if head_task == self.tail:
self.tail = "head"
return rt_value
return None def test_output(self, name=""):
print >>sys.stderr, name
print >>sys.stderr, "-" * 10 + "TEST_OUTPUT" + "-" * 10
print >>sys.stderr, "Tail: %s\nHead: %s\nLength: %s" % (self.getTail(), self.getHead(), self.__len__())
head = "head"
while head != "null":
print >>sys.stderr, "%s\t%s\t%s" % (head, self.map[head]["stat"], self.map[head]["next"])
head = self.map[head]["next"]
print >>sys.stderr, "-" * 31 class OrderedMapQueue(Queue.Queue):
''' ordered-map queue '''
def _init(self, maxsize=0):
self.queue = Link() def _put(self, item):
self.queue.add(item) def _get(self):
return self.queue.pop() def _qsize(self):
return self.queue.__len__() if __name__ == "__main__":
#mylink = Link()
#mylink.add("task1","-1")
#mylink.add("task2","-2")
#mylink.add("task3","-1")
#mylink.test_output() myqueue = OrderedMapQueue()
myqueue.put("task2\t-2")
myqueue.put("task3\t-1")
myqueue.put("task1\t-2")
myqueue.put("task3\t-1")
myqueue.put("task3\t-2")
myqueue.queue.test_output()
print myqueue.get()
myqueue.queue.test_output()
print myqueue.get()
myqueue.queue.test_output()
print myqueue.get()
myqueue.queue.test_output()
自己菜鸟一只,其中肯定有不少问题或者可改进的,希望大家能多多支出,我定会认真修改,多谢~
另外,推荐几个拓展Queue的连接:
http://stackoverflow.com/questions/16506429/check-if-element-is-already-in-a-queue/16506527#16506527
http://stackoverflow.com/questions/8482619/proper-way-to-extend-python-queue
【Python】:拓展Queue实现有序不重复队列的更多相关文章
- python多进程之间的通信:消息队列Queue
python中进程的通信:消息队列. 我们知道进程是互相独立的,各自运行在自己独立的内存空间. 所以进程之间不共享任何变量. 我们要想进程之间互相通信,传送一些东西怎么办? 需要用到消息队列!! 进程 ...
- python基础 — Queue 队列
queue介绍 queue是python中的标准库,俗称队列. 在python中,多个线程之间的数据是共享的,多个线程进行数据交换的时候,不能够保证数据的安全性和一致性,所以当多个线程需要进行数据交换 ...
- python【第十一篇】消息队列RabbitMQ、缓存数据库Redis
大纲 1.RabbitMQ 2.Redis 1.RabbitMQ消息队列 1.1 RabbitMQ简介 AMQP,即Advanced Message Queuing Protocol,高级消息队列协议 ...
- Python实现的数据结构与算法之队列详解
本文实例讲述了Python实现的数据结构与算法之队列.分享给大家供大家参考.具体分析如下: 一.概述 队列(Queue)是一种先进先出(FIFO)的线性数据结构,插入操作在队尾(rear)进行,删除操 ...
- Python之路,Day10 - 异步IO\数据库\队列\缓存
Python之路,Day9 - 异步IO\数据库\队列\缓存 本节内容 Gevent协程 Select\Poll\Epoll异步IO与事件驱动 Python连接Mysql数据库操作 RabbitM ...
- Python之Queue模块
Queue 1.创建一个“队列”对象 >>> import Queue >>> queue = Queue.Queue(maxsize=100) >>& ...
- Python中Queue模块及多线程使用
Python的Queue模块提供一种适用于多线程编程的FIFO实现.它可用于在生产者(producer)和消费者(consumer)之间线程安全(thread-safe)地传递消息或其它数据,因此多个 ...
- Python开发基础-Day31 Event对象、队列和多进程基础
Event对象 用于线程间通信,即程序中的其一个线程需要通过判断某个线程的状态来确定自己下一步的操作,就用到了event对象 event对象默认为假(Flase),即遇到event对象在等待就阻塞线程 ...
- python之Queue
一.多进程的消息队列 “消息队列”是在消息的传输过程中保存消息的容器 消息队列最经典的用法就是消费者和生成者之间通过消息管道来传递消息,消费者和生成者是不通的进程.生产者往管道中写消息,消费者从管道中 ...
随机推荐
- Tricks(四十八)—— 注释一段代码
为 if 的条件判断表达式,传一个永假的语句,来注释一段代码: # Python if False: ... ... ... # C/C++ if (false) { ... ... } 永远不要直接 ...
- Azure 与 AI
微软 Build 2017 开发者大会:Azure 与 AI 的快速发展 欢迎大家持续关注葡萄城控件技术团队博客,更多更好的原创文章尽在这里~~ 一年一度的微软 Build 大会准时起航,本年度大 ...
- 理解Java字符串常量池与intern()方法
String s1 = "Hello"; String s2 = "Hello"; String s3 = "Hel" + "lo ...
- 【records】10.24..10.30
做的题越来越少了; 我是不是该学下网络流.
- Atititjs javascript异常处理机制java异常转换.js exception process
Atititjs javascript异常处理机制java异常的转换.js exception process 1. javascript异常处理机制 Throw str Not throw erro ...
- matlab 读写其他格式数据文件(excel)
1. excel matlab和excel 中的数据互相导入 xlswrite() mat ⇒ excel 请问怎么把大容量的mat文件导出到excel文件中 – MATLAB中文论坛 % data. ...
- Linux性能测试 pmap命令
名称: pmap - report memory map of a process(查看进程的内存映像信息)用法 pmap [ -x | -d ] [ -q ] pids... ...
- ASP.NET Core 项目配置 ( Startup ) - ASP.NET Core 基础教程 - 简单教程,简单编程
原文:ASP.NET Core 项目配置 ( Startup ) - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 项目配置 ( Startup ) 前面几章节 ...
- matlab GUI 编程
matlab 语法的简便,在 GUI 上也不遑多让呀: uigetfile [filename, pathname] = uigetfile('*.m', 'choose a m file') 1. ...
- 好玩的WPF第三弹:颤抖吧,地球!消失吧,地球!
原文:好玩的WPF第三弹:颤抖吧,地球!消失吧,地球! 版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net ...