Delayqueue (Python implementation)

Source: Internet
Author: User

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 ( ()) while Delta > 0:SELF.CAN_DONE.W AIT (delta) task = Self.peek () Delta = total_secOnds ( ()) 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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.