Cause: A few years ago in order to develop a monitoring system, need to periodically check the system state, so need to add to the inspection task, queued (by Time), remove and other operations, inadvertently found in the Java JDK Delayqueue, so implemented a python version
The source code is as follows:
#-*-Coding:utf-8-*-# python version of Delayqueue class and delayed interface # from Queue import priorityqueue from datetime import Date Time import threading class delayed (object): # Return: Scheduled execution times # units: DateTime def plan_time (self): Pass de F Total_seconds (TD): Return (Td.microseconds + (td.seconds + td.days * 3600) * 10**6)/10**6 class Delayqueue (
Priorityqueue): Def __init__ (self, maxsize): Self.queue = [] # If the task does not arrive at execution time, then the consumer must wait on this condition Self.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 if the queue does not exist
Period delay element, then wait for it def Take_task (self): Self.can_done.acquire () Try:task = Self.peek () Delta = total_seconds (Task.plan_time-datetime.now ()) while Delta > 0:SELF.CAN_DONE.W AIT (delta) task = Self.peek () Delta = total_secOnds (Task.plan_time-datetime.now ()) item = Self.get () self.can_done.notify_all () re
Turn item[1] finally:self.can_done.release () def peek (self): Self.not_empty.acquire ()
Try:while not Self._qsize (): Self.not_empty.wait () return self.queue[0][1]
Finally:self.not_empty.release ()
The Priorityqueue in the
Ps:python is based on the minimum heap algorithm, and the time it takes to add and remove an element is log2 (n)