set timeout in python function

How to Set Timeout on Function Call in Python

Sometimes you may need set time limit on function call or limit execution time on function call in Python. This is especially required if you have long running functions. In this article, we will learn how to set timeout on function call in Python.


How to Set Timeout on Function Call in Python

You can easily set timeout for python functions, using signal library. Here are the steps for the same.

1. Import Signal Module

The first step is to import signal module. This package is already installed by default in every Python version.

import signal

2. Create Signal Handler

Next, we define a signal handler function that is called when timeout occurs. In our case, we simply raise an exception and display a message.

def handler(signum, frame):
    print("Forever is over!")
    raise Exception("end of time")

3. Create long running function

Next, we define a long running function that runs forever. You can modify it as per your requirement.

def loop_forever():
     import time
     while 1:
         print("sec")
         time.sleep(1)

4. Register Signal Function Handler

We register signal function handler with the following command.

signal.signal(signal.SIGALRM, handler)

The above line means that whenever signal.SIGALRM signal is triggered, handler function is called.

5. Define Timeout For Function

Next, we define a timeout of 10 seconds for function. This means that after 10 seconds signal.SIGALRM will be triggered.

signal.alarm(10)

6. Call Function

Finally, we call the long running function.

try:
     loop_forever()
 except Exception as exc: 
     print(exc)

You will see the following output. If you get syntax error in above code, try using ‘except Exception, exc’ instead.

sec
sec
sec
sec
sec
sec
sec
sec
Forever is over!
end of time

You will see that the function is stopped after 10 seconds and timeout message is displayed in the output.

Please note, the handler function is called 10 seconds after the signal.alarm(10) is called and not when the long running function is called. After timeout, it raises an exception that can be used in regular python code.

In this article, we have learnt how to set timeout on function in python. This is very useful to prevent long running functions from blocking your system resources and affecting performance.

Also read:

How to Set Default Value for Datetime Column in MySQL
How to Empty Array in JavaScript
How to Set Query Timeout in MySQL
How to Count Frequency of Array Items in JavaScript
How to Allow Only Alphabet Input in HTML Text Input

3 thoughts on “How to Set Timeout on Function Call in Python

Leave a Reply

Your email address will not be published. Required fields are marked *