-
Notifications
You must be signed in to change notification settings - Fork 1
/
repeatingtimer.py
73 lines (58 loc) · 1.47 KB
/
repeatingtimer.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python2.7
"""
Run a task repeatedly at a fixed interval.
"""
#
# IMPORTS
#
import time
import threading
#
# CLASSES
#
class RepeatingTimer:
def __init__(self, interval, target, thread=None, name=None):
if not thread:
thread = threading.Thread(target=self._run, name=name, args=(interval, target))
self.thread = thread
self.cancelled = False # thread-safe by rule of the interpreter (see http://effbot.org/zone/thread-synchronization.htm)
def _run(self, interval, target):
next = time.time() + interval
while True:
self._sleep_until(next)
if self.cancelled:
break
# else, call the target function and the re-loop for the next interval
target()
next += interval
def _sleep_until(self, t):
left = t - time.time()
while left > 0:
time.sleep(left)
left = t - time.time()
def cancel(self):
self.cancelled = True
def start(self):
# bombs if thread has already been started
self.thread.start()
#
# MAIN
#
def main():
""" Super-dumb test. """
# override annoying python SIGINT handling
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
def printit():
print time.time(), 'tick!'
timer = RepeatingTimer(5, printit)
print time.time(), 'starting'
timer.start()
time.sleep(22)
print time.time(), 'cancelling'
timer.cancel()
print time.time(), 'joining'
timer.thread.join()
print time.time(), 'and.... done!'
if __name__ == "__main__":
main()