-
Notifications
You must be signed in to change notification settings - Fork 1
/
timer.py
54 lines (42 loc) · 1.38 KB
/
timer.py
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from observe import Observable
import time
class Timer(Observable):
def __init__(self, owner=None):
"""
:param owner: An optional Observable to send the timeout event from
"""
Observable.__init__(self)
# for general tick
self.prevtime = time.time()
# for stopwatch timing
self.start = None
self.threshold = None
if owner is not None:
self.owner = owner
else:
self.owner = self
def startwatch(self, seconds):
self.start = time.time()
self.threshold = seconds
def stopwatch(self):
self.start = None
self.threshold = None
# todo: return diff
def is_timing(self):
"""
Check if timer is currently running
:return: boolean, True if startwatch() has been called and timeout has not yet been reached
"""
return self.start is not None and self.threshold is not None
def tick(self):
curtime = time.time()
diff = curtime - self.prevtime
self.prevtime = curtime
# if stop watch is running
if self.start:
if (curtime - self.start) > self.threshold:
# allows the callback to start another timer
self.stopwatch()
self.owner.notify("timeout")
self.notify("tick", diff=diff)
return diff