Alireza
Alireza

Reputation: 6848

How to set timeout for thread in case of no response and terminate the thread?

Let's say we have a code sample as below which prints hello, world after 5 seconds. I want a way to check if Timer thread took more than 5 seconds then terminate the thread.

from threading import Timer
from time import sleep


def hello():
    sleep(50)
    print "hello, world"

t = Timer(5, hello)
# after 5 seconds, "hello, world" will be printed
t.start()

In the above code block hello will take more than 5 seconds to process.

consider hello function, a call to outside server that returns no response and even no exception for timeout or anything! I wanted to simulate the issue with sleep function.

Upvotes: 2

Views: 2625

Answers (1)

emmanuelsa
emmanuelsa

Reputation: 687

You can use signal and call its alarm method. An exception (which you can handle) will be raised after the timeout time has passed. See an (incomplete) example below.

import signal

class TimeoutException (Exception):
    pass

def signalHandler (signum, frame):
    raise TimeoutException ()

timeout_duration = 5

signal.signal (signal.SIGALRM, signalHandler)
signal.alarm (timeout_duration)

try:
    """Do something that has a possibility of taking a lot of time 
    and exceed the timeout_duration"""
except TimeoutException as exc:
    "Notify your program that the timeout_duration has passed"
finally:
    #Clean out the alarm
    signal.alarm (0)

You can read more about Python's signal here https://docs.python.org/2/library/signal.html.

Upvotes: 2

Related Questions