I have a long-running thread which calls a method. I want to implement a timeout for a method which takes more than a certain time and exit the method but not thread.
Note: My use case is(Objective), I have a thread which continuously polls from a real-time data stream and process it with some method(which might end up taking infinite time for certain data point). So I want to timeout the method but not thread so that I can keep polling the real-time data.
Below is the sample code which I'm trying to fix it. It works when we start a single thread and an exception is created but with more than 1 thread signal doesn't work.
from threading import Thread
import time
import signal
def random_func(a):
time.sleep(a)
return True
class TimeoutException(Exception): # Custom exception class
pass
def timeout_handler(signum, frame): # Custom signal handler
raise TimeoutException
signal.signal(signal.SIGALRM, timeout_handler)
class CheckThreadSignal(Thread):
def __init__(self, thread_id):
self.thread_id = thread_id
super().__init__()
def run(self):
c = 0
while True:
signal.alarm(5)
try:
if self.thread_id == 2 and c == 10:
random_func(10)
else:
random_func(0.1)
except TimeoutException:
print("signal: {}".format(self.thread_id), e)
continue
else:
signal.alarm(0)
print("running: {}, count: {}".format(self.thread_id, c))
time.sleep(0.1)
c+=1
CheckThreadSignal(0).start()
CheckThreadSignal(2).start()