pymen

Untitled

Sep 6th, 2013
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. import collections
  2. import threading
  3.  
  4. class ExpiredDeque:
  5.     """Tracks how many events were added in the preceding time period
  6.    """
  7.     def __init__(self, timeout=1):
  8.         self.lock=threading.Lock()
  9.         self.timeout = timeout
  10.         self.events = collections.deque()
  11.  
  12.     def add(self,item):
  13.         """Add event time
  14.        """
  15.         if item in self:
  16.             print "Cant process the same request from %s in short time (%s sec)" % (item, self.timeout)
  17.             return False
  18.  
  19.         with self.lock:
  20.             self.events.append(item)
  21.             threading.Timer(self.timeout,self.expire).start()
  22.             return  True
  23.  
  24.     def __len__(self):
  25.         """Return number of active events
  26.        """
  27.         with self.lock:
  28.             return len(self.events)
  29.  
  30.     def expire(self):
  31.         """What should we do when value expires
  32.        Remove any expired events
  33.        """
  34.         with self.lock:
  35.             val = self.events.popleft()
  36.             print "expired %s" % val
  37.  
  38.     def __str__(self):
  39.         with self.lock:
  40.             return str(self.events)
  41.  
  42.     def __contains__(self, val):
  43.         with self.lock:
  44.             return val in self.events
  45.  
  46.  
  47. import time
  48. import datetime
  49. c = ExpiredDeque()
  50. assert(len(c) == 0)
  51. print(c)
  52. # deque([])
  53.  
  54. c.add('BOB')
  55. c.add('BOB')
  56. time.sleep(0.75)
  57. c.add('SANDY')
  58. assert(len(c) == 2)
  59. print(c)
  60.  
  61. time.sleep(0.75)
  62. assert(len(c) == 1)
  63. print(c)
  64.  
  65. time.sleep(0.75)
  66. assert(len(c) == 0)
Advertisement
Add Comment
Please, Sign In to add comment