Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

container where values expire in python

I am after a thread safe Python container where the values are automatically removed after a time. Does such a class exist?

like image 253
hoju Avatar asked Nov 18 '10 21:11

hoju


1 Answers

Here is a thread safe version of ExpireCounter:

import datetime
import collections
import threading

class ExpireCounter:
    """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
        """
        with self.lock:
            self.events.append(item)
            threading.Timer(self.timeout,self.expire).start()

    def __len__(self):
        """Return number of active events
        """
        with self.lock:
            return len(self.events)

    def expire(self):
        """Remove any expired events
        """
        with self.lock:
            self.events.popleft()

    def __str__(self):
        with self.lock:
            return str(self.events)

which can be used like this:

import time
c = ExpireCounter()
assert(len(c) == 0)
print(c)
# deque([])

c.add(datetime.datetime.now())
time.sleep(0.75)
c.add(datetime.datetime.now())    
assert(len(c) == 2)
print(c)
# deque([datetime.datetime(2010, 11, 19, 8, 50, 0, 91426), datetime.datetime(2010, 11, 19, 8, 50, 0, 842715)])

time.sleep(0.75)
assert(len(c) == 1)
print(c)
# deque([datetime.datetime(2010, 11, 19, 8, 50, 0, 842715)])
like image 123
unutbu Avatar answered Nov 07 '22 17:11

unutbu