-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathPeriodicExecutor.py
More file actions
82 lines (58 loc) · 1.58 KB
/
Copy pathPeriodicExecutor.py
File metadata and controls
82 lines (58 loc) · 1.58 KB
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
74
75
76
77
78
79
80
81
82
import threading
class PeriodicExecutor(threading.Thread):
def __init__(self, interval, func, **kwargs):
""" Execute func(params) every 'interval' seconds """
threading.Thread.__init__(self, name="PeriodicExecutor")
self.setDaemon(1)
self._finished = threading.Event()
self._interval = interval
self._func = func
self._params = kwargs
self.start()
def setInterval(self, interval):
"""Set the number of seconds we sleep between executing our task"""
self._interval = interval
def shutdown(self):
"""Stop this thread"""
self._finished.set()
def run(self):
while 1:
if self._finished.isSet(): return
self._func(**self._params)
# sleep for interval or until shutdown
self._finished.wait(self._interval)
#
## Example 1:
#
import time
def schreib(text):
print(text)
one = PeriodicExecutor(5, schreib, text="Hallo Welt!")
time.sleep(5)
one.setInterval(10)
two = PeriodicExecutor(2, schreib, text="bla")
time.sleep(4)
two.setInterval(3)
three = PeriodicExecutor(5, schreib, text="Bye!")
time.sleep(5)
one.shutdown()
two.shutdown()
three.shutdown()
time.sleep(2)
print("Quit")
#
## Example 2:
#
import signal
def schreib(text):
print(text)
one = PeriodicExecutor(5, schreib, text="Hallo Welt!")
two = PeriodicExecutor(2, schreib, text="bla")
three = PeriodicExecutor(5, schreib, text="Bye!")
try: signal.pause()
except KeyboardInterrupt: pass
one.shutdown()
two.shutdown()
three.shutdown()
print("Quit")
#EOF