dc4627b3565d05882d8d1f4d6cb8a687aef01e08
[saartuer.git] / waker.py
1 from libtuer import ThreadRepeater
2 from collections import namedtuple
3 from threading import Lock
4
5 SLEEP_TIME = 0.5
6
7 ToBeWoken = namedtuple('ToBeWoken','f period time_since_call one_shot')
8
9 class Waker():
10         def __init__(self):
11                 self._tobewokens = []
12                 self._tobewokens_lock = Lock()
13                 self._t = ThreadRepeater(self._wake, SLEEP_TIME, name="Waker")
14         
15         def register(self, f, time, one_shot = False):
16                 '''Register a function which is called approximately every <time> seconds (or just once, if one_shot is True). f should return quickly, or it will delay the waker!'''
17                 time = max(time//SLEEP_TIME, 1)
18                 with self._tobewokens_lock:
19                         self._tobewokens.append(ToBeWoken(f, time, 0, one_shot))
20         
21         def _wake(self):
22                 with self._tobewokens_lock:
23                         delete = []
24                         # run the functions we ought to run
25                         for tobewoken, idx in zip(self._tobewokens, range(len(self._tobewokens))):
26                                 tobewoken.time_since_call += 1
27                                 if tobewoken.time_since_call >= tobewoken.period:
28                                         tobewoken.f()
29                                         tobewoken.time_since_call = 0
30                                         if tobewoken.one_shot:
31                                                 delete.append(idx)
32                         # delete what we have to delete - in reverse order so the indices stay valid!
33                         delete.reverse()
34                         for idx in delete:
35                                 del self._tobewokens[idx]
36         
37         def stop(self):
38                 self._t.stop()