Last active
May 26, 2022 14:28
-
-
Save thevickypedia/46a3de1986536fc2d344fb46c169c4f2 to your computer and use it in GitHub Desktop.
Handle timeout using multiprocessing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import multiprocessing | |
import time | |
from typing import Callable, Union | |
class TimeoutHandler: | |
"""Initiates TimeoutHandler object to run a function and terminate it after a given time limit. | |
>>> TimeoutHandler | |
""" | |
def __init__(self, timeout: Union[int, float]): | |
"""Instantiates necessary args. | |
Args: | |
timeout: Timeout after which the said function has to be terminated. | |
""" | |
self.timeout = timeout | |
def run(self, function: Callable, *args, **kwargs) -> str: | |
"""Runs the given function. | |
Args: | |
function: Function to run and timeout. | |
*args: Args to be passed to the function. | |
**kwargs: Keyword args to be passed to the function. | |
Returns: | |
str: | |
Status if the function has completed within the given timeout or not. | |
""" | |
proc = multiprocessing.Process(target=function, args=args, kwargs=kwargs) | |
_start = time.time() | |
proc.start() | |
proc.join(timeout=self.timeout) | |
if proc.is_alive(): | |
proc.kill() | |
return f"Function [{function.__name__}] exceeded {self.timeout} seconds. Process PID [{proc.pid}] killed!" | |
return f"Function [{function.__name__}] finished in {round(float(time.time() - _start), 2)} seconds" | |
def sleeper(interval, name): | |
time.sleep(interval) | |
print("Successful") | |
if __name__ == '__main__': | |
start = time.time() | |
print(TimeoutHandler(timeout=5).run(function=sleeper, **{"interval": 3, "name": "Vicky"})) | |
print(time.time() - start) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment