-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtimer.py
More file actions
38 lines (31 loc) · 1023 Bytes
/
timer.py
File metadata and controls
38 lines (31 loc) · 1023 Bytes
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
import time
from threading import Event, Thread
class RepeatedTimer(object):
'''
Repeater class that call the function every interval seconds.
'''
def __init__(self, interval, function, *args, **kwargs):
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.started = time.time()
self.event = Event()
self.thread = Thread(target=self._target)
self._started = False
def _target(self):
while not self.event.wait(self._time):
self.function(*self.args, **self.kwargs)
@property
def _time(self):
return self.interval - ((time.time() - self.started) % self.interval)
def start(self):
if not self._started:
self._started = True
self.thread.setDaemon(True)
self.thread.start()
def stop(self):
if self._started:
self._started = False
self.event.set()
self.thread.join()