-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreads.py
48 lines (33 loc) · 1.07 KB
/
threads.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
from threading import Thread, Event, RLock
_THREADS = set()
rlock = RLock()
def threads_shutdown():
while _THREADS:
for t in _THREADS.copy():
t.stop()
class StoppableThread(Thread):
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None):
if kwargs is None:
kwargs = {}
self.stopping = Event()
super(StoppableThread, self).__init__(group, target, name, args, kwargs)
def start(self):
self.stopping.clear()
_THREADS.add(self)
super(StoppableThread, self).start()
def stop(self):
self.stopping.set()
self.join()
def join(self):
super(StoppableThread, self).join()
_THREADS.discard(self)
class Interval(StoppableThread):
def __init__(self, sec, func):
super(Interval, self).__init__(target=self.set_interval, args=(func, sec))
self.daemon = True
def set_interval(self, sec, func):
while not self.stopping.wait(sec):
try:
func()
except:
pass