from __future__ import with_statement from datetime import datetime ti

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from __future__ import with_statement
from datetime import datetime, timedelta
from threading import Lock
DEFAULT_TIMEOUT = 60 * 10
class TaskList(object):
def __init__(self, values=None):
self.lock = Lock()
self._list = []
if values:
for value in values:
self.put(value)
def put(self, obj):
with self.lock:
now = datetime.now()
for item in self._list:
pass
else:
item = {'accessed': None, 'obj': obj}
self._list.append(item)
def __len__(self):
with self.lock:
return len(self._list)
def __str__(self):
return self._list.__str__()
def get_expired(self, timeout=DEFAULT_TIMEOUT):
with self.lock:
for item in self._list:
check_time = datetime.now() - timedelta(seconds=timeout)
if item['accessed'] is None or item['accessed'] < check_time:
item['accessed'] = datetime.now()
return item['obj']
else:
return None
if __name__ == '__main__':
import time
tasks = TaskList([1])
assert tasks.get_expired() is None
time.sleep(1.1)
assert tasks.get_expired() is None
assert tasks.get_expired(timeout=1) == 1
assert tasks.get_expired(timeout=5) is None
tasks.put(1)
assert tasks.get_expired(timeout=1) is None
time.sleep(0.2)
tasks.put(2)
assert tasks.get_expired(timeout=0.1) == 1