silence sphinx a bit
[saartuer.git] / waker.py
1 from libtuer import ThreadRepeater
2 from threading import Lock
3
4 SLEEP_TIME = 0.5
5
6 class ToBeWoken:
7         '''a simple struct storing information about a to-be-woken function'''
8         def __init__(self, f, period, one_shot):
9                 self.f = f
10                 self.period = period
11                 self.time_since_call = 0
12                 self.one_shot = one_shot
13
14 class Waker():
15         def __init__(self):
16                 self._tobewokens = []
17                 self._tobewokens_lock = Lock()
18                 self._t = ThreadRepeater(self._wake, SLEEP_TIME, name="Waker")
19         
20         def register(self, f, time, one_shot = False):
21                 '''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!'''
22                 time = max(time//SLEEP_TIME, 1)
23                 with self._tobewokens_lock:
24                         self._tobewokens.append(ToBeWoken(f, time, one_shot))
25         
26         def _wake(self):
27                 with self._tobewokens_lock:
28                         delete = []
29                         # run the functions we ought to run
30                         for tobewoken, idx in zip(self._tobewokens, range(len(self._tobewokens))):
31                                 tobewoken.time_since_call += 1
32                                 if tobewoken.time_since_call >= tobewoken.period:
33                                         tobewoken.f()
34                                         tobewoken.time_since_call = 0
35                                         if tobewoken.one_shot:
36                                                 delete.append(idx)
37                         # delete what we have to delete - in reverse order so the indices stay valid!
38                         delete.reverse()
39                         for idx in delete:
40                                 del self._tobewokens[idx]
41         
42         def stop(self):
43                 self._t.stop()