-
Notifications
You must be signed in to change notification settings - Fork 2
/
job.py
53 lines (42 loc) · 1.44 KB
/
job.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
import signal
import threading
import time
class DaemonKilled(Exception):
def __init__(self, signum, handler):
super().__init__()
self.__signum = signum
self.__handler = handler
def get_signal(self):
return self.__signum
class Job(threading.Thread):
def __init__(self, logger, interval, execute, *args, **kwargs):
threading.Thread.__init__(self)
self.daemon = True
self.stopped = threading.Event()
self.interval = interval
self.execute = execute
self.logger = logger
self.args = args
self.kwargs = kwargs
signal.signal(signal.SIGTERM, self.signal_handler)
signal.signal(signal.SIGINT, self.signal_handler)
def signal_handler(self, signum, handler):
raise DaemonKilled(signum, handler)
def stop(self):
self.stopped.set()
self.join()
def run(self):
while not self.stopped.wait(self.interval.total_seconds()):
self.execute(*self.args, **self.kwargs)
def start(self):
super().start()
while True:
try:
time.sleep(1)
except DaemonKilled as ex:
if ex.get_signal() == signal.SIGINT:
self.logger.info('Terminated by SIGINT')
elif ex.get_signal() == signal.SIGTERM:
self.logger.info('Terminated by SIGTERM')
self.stop()
break