I have been trying to create an timeout that tells a section of my code to move on if it hasn't reached a result within a certain amount of time.
I tested the code from the main answer posted here: break the function after certain time , and it works perfectly however when I implemented it with my code it does not work.
The TimeoutException is never being triggered no matter how long it takes for the block of code within the 'Try' to execute. The timer within this block of code consistently prints out as greater than 5 seconds even though the print action should not even be called if the code takes longer than the 5 seconds allowed by signal.alarm(5).
Can you think of any reasons that the TimeoutException is not being triggered and how I can fix it?
import signal
import time
def evaluateList(dataDictionaryList):
newDataDict = []
count = 0
class TimeoutException(Exception):
pass
def timeout_handler(signum, frame):
raise TimeoutException
signal.signal(signal.SIGALRM, timeout_handler)
for dataDictionary in dataDictionaryList:
signal.alarm(5)
try:
startTime = time.time()
newDataDict.append(functionThatMightHang(dataDictionary))
print(count + 1, ' Time to evaluate: ', time.time() - startTime)
count+=1
except TimeoutException:
print('took too long')
continue
else:
signal.alarm(0)
return newDataDict