Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import collections
- import threading
- class ExpiredDeque:
- """Tracks how many events were added in the preceding time period
- """
- def __init__(self, timeout=1):
- self.lock=threading.Lock()
- self.timeout = timeout
- self.events = collections.deque()
- def add(self,item):
- """Add event time
- """
- if item in self:
- print "Cant process the same request from %s in short time (%s sec)" % (item, self.timeout)
- return False
- with self.lock:
- self.events.append(item)
- threading.Timer(self.timeout,self.expire).start()
- return True
- def __len__(self):
- """Return number of active events
- """
- with self.lock:
- return len(self.events)
- def expire(self):
- """What should we do when value expires
- Remove any expired events
- """
- with self.lock:
- val = self.events.popleft()
- print "expired %s" % val
- def __str__(self):
- with self.lock:
- return str(self.events)
- def __contains__(self, val):
- with self.lock:
- return val in self.events
- import time
- import datetime
- c = ExpiredDeque()
- assert(len(c) == 0)
- print(c)
- # deque([])
- c.add('BOB')
- c.add('BOB')
- time.sleep(0.75)
- c.add('SANDY')
- assert(len(c) == 2)
- print(c)
- time.sleep(0.75)
- assert(len(c) == 1)
- print(c)
- time.sleep(0.75)
- assert(len(c) == 0)
Advertisement
Add Comment
Please, Sign In to add comment