change the way the waker works: let others register to be called by it
[saartuer.git] / waker.py
1 from libtuer import ThreadRepeater
2 from collections import namedtuple
3
4 SLEEP_TIME = 0.5
5
6 ToBeWoken = namedtuple('ToBeWoken','f period time_since_call one_shot')
7
8 class Waker():
9         def __init__(self, sm):
10                 self._sm = sm
11                 self._t = ThreadRepeater(self._wake, SLEEP_TIME, name="Waker")
12                 self._tobewokens = []
13         
14         def register(f, time, one_shot = False):
15                 '''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!'''
16                 time = max(time//SLEEP_TIME, 1)
17                 self._tobewokens.append(ToBeWoken(f, time, 0, one_shot))
18         
19         def _wake(self):
20                 delete = []
21                 # run the functions we ought to run
22                 for tobewoken, idx in zip(self._tobewokens, range(len(self._tobewokens))):
23                         tobewoken.time_since_call += 1
24                         if tobewoken.time_since_call >= tobewoken.period:
25                                 tobewoken.f()
26                                 tobewoken.time_since_call = 0
27                                 if tobewoken.one_shot:
28                                         delete.append(idx)
29                 # delete what we have to delete - in reverse order so the indices stay valid!
30                 delete.reverse()
31                 for idx in delete:
32                         del self._tobewokens[idx]
33         
34         def stop(self):
35                 self._t.stop()