1 from libtuer import ThreadRepeater
2 from threading import Lock
7 '''a simple struct storing information about a to-be-woken function'''
8 def __init__(self, f, period, one_shot):
11 self.time_since_call = 0
12 self.one_shot = one_shot
17 self._tobewokens_lock = Lock()
18 self._t = ThreadRepeater(self._wake, SLEEP_TIME, name="Waker")
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, 0, one_shot))
27 with self._tobewokens_lock:
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:
34 tobewoken.time_since_call = 0
35 if tobewoken.one_shot:
37 # delete what we have to delete - in reverse order so the indices stay valid!
40 del self._tobewokens[idx]