-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer_threads.py
46 lines (38 loc) · 1.28 KB
/
timer_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
import os
import re
from threading import Timer
"""
(Borrowed from https://stackoverflow.com/a/13151299/9458555)
Creates Timer threads for the purpose of executing functions every interval of n
https://docs.python.org/3/library/threading.html#timer-objects
"""
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
multipliers = {"s": 1, "m": 60, "h": 3600, "d": 86400}
if re.search("[\D]", interval):
try:
unit = interval[-1:]
self.interval = multipliers[unit] * int(interval[:-1])
except KeyError:
print('Unsupported interval "%s"!' % unit)
os._exit(1)
else:
self.interval = int(interval)
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False