Limit execution time of a function call in Python


Python tip:

You can limit the execution time of a function by using the signal library.

An example👇

import signal
import time


def handle_timeout(signum, frame):
    raise TimeoutError


def my_task():
    for i in range(6):
        print(f"I am working something long running, step {i}")
        time.sleep(1)


signal.signal(signal.SIGALRM, handle_timeout)
signal.alarm(5)  # 5 seconds

try:
    my_task()
except TimeoutError:
    print("It took too long to finish the job")
finally:
    signal.alarm(0)


"""
I am working something long running, step 0
I am working something long running, step 1
I am working something long running, step 2
I am working something long running, step 3
I am working something long running, step 4
It took too long to finish the job
"""