Cause: A few years ago in order to develop a monitoring system, it was necessary to periodically check the status of the system, so it was necessary to add, queue (by Time), remove and so on, and inadvertently discovered that there was delayqueue in the Java JDK, thus implementing a Python version
The source code is as follows:
#-*-Coding:utf-8-*-# python version of the Delayqueue class and Delayed interface# fromQueueImportPriorityqueue fromDatetimeImportDatetimeImportThreading class Delayed(object): # return: Scheduled execution time # units: DateTime def plan_time(self): Pass def total_seconds(TD): return(Td.microseconds + (td.seconds + td.days * -*3600) *Ten**6) /Ten**6 class delayqueue(priorityqueue): def __init__(self, maxsize):Self.queue = []# If the task does not reach execution time, then the consumer must wait on this conditionSelf.lock = Threading. Lock () Self.can_done = Threading. Condition (Self.lock) def put_task(self, Task):Self.put ((task.plan_time, Task))# Retrieves and removes the header of this queue, and waits for an element that does not have an expiration delay if this queue does not exist def take_task(self):Self.can_done.acquire ()Try: task = Self.peek () Delta = total_seconds (Task.plan_time-datetime.now ()) whileDelta >0: self.can_done.wait (Delta) task = Self.peek () Delta = total_seconds (task.pla N_time-datetime.now ()) item = Self.get () self.can_done.notify_all ()returnitem[1]finally: Self.can_done.release () def Peek(self):Self.not_empty.acquire ()Try: while notSelf._qsize (): Self.not_empty.wait ()returnself.queue[0][1]finally: Self.not_empty.release ()
Priorityqueue in Ps:python based on the minimal heap algorithm, adding and removing an element is time consuming log2 (n)
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Delayqueue (Python implementation)