-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalarm.py
41 lines (28 loc) · 863 Bytes
/
alarm.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
import signal
import threading
from contextlib import contextmanager
def _signal_timer(timeout, callback):
def wrapper(*args):
return callback()
signal.signal(signal.SIGALRM, wrapper)
signal.alarm(timeout)
def reset():
return signal.alarm(0)
return reset
def _threading_timer(timeout, callback):
timer = threading.Timer(timeout, callback)
timer.start()
def reset():
return timer.cancel()
return reset
def alarm_create(timeout, callback, use_signal=True):
import platform
if use_signal and platform.system() != "Windows": # SIGALRM does not work on Windows
return _signal_timer(timeout, callback)
else:
return _threading_timer(timeout, callback)
@contextmanager
def alarm_context(*args, **kwargs):
reset = alarm_create(*args, **kwargs)
yield
reset()