Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time;
- now = time.time;
- debug_mode = False;
- def debug_print(message):
- if debug_mode:
- print "[TimedCollection]: %s" % (message);
- class TimedObject:
- def __init__(self, obj, lifetime):
- self.obj = obj;
- self.timestamp = now();
- self.lifetime = lifetime;
- self.expire_flag = False;
- def __str__(self):
- return str(self.obj);
- def expired(self):
- if self.expire_flag:
- return True;
- current_time = now();
- if current_time - self.timestamp > self.lifetime:
- self.expire_flag = True;
- return True;
- return False;
- def get_object(self):
- return self.obj;
- class TimedCollection:
- DEFAULT_LIFETIME = 5.0; # seconds
- def __init__(self, lifetime=DEFAULT_LIFETIME):
- self.objs = [];
- self.lifetime = lifetime;
- def __delitem__(self, item):
- self.remove(item);
- def __len__(self):
- return len(self.objs);
- def set_lifetime(self, lifetime):
- debug_print("Lifetime=%f" % (lifetime));
- self.lifetime = lifetime;
- def add(self, obj, lifetime=None):
- if lifetime == None:
- lifetime = self.lifetime;
- debug_print("Added %s (lifetime=%f)" % (str(obj), lifetime));
- self.objs.append(TimedObject(obj, lifetime));
- def remove(self, obj):
- debug_print("Removing %s" % (str(obj)));
- index = self.index_of(obj);
- if index < 0:
- return False;
- del self.objs[index];
- return True;
- def index_of(self, obj):
- for n in xrange(0, len(self.objs)):
- if self.objs[n] == obj:
- return n;
- return -1;
- def clear(self):
- debug_print("Cleared");
- del self.objs;
- self.objs = [];
- def update(self):
- remove_list = [];
- for item in self.objs:
- if item.expired():
- remove_list.append(item);
- for item in remove_list:
- assert self.remove(item);
- if __name__ == '__main__':
- # Run tests.
- debug_mode = False;
- col = TimedCollection();
- col.set_lifetime(5.0);
- col.add("hi");
- col.add("how are you?", 7.5);
- col.add("what's up?", 9.0);
- seconds_passed = 0;
- while len(col) != 0:
- time.sleep(1.0);
- col.update();
- seconds_passed += 1;
- assert seconds_passed < 15;
- debug_print("Testing successful.");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement