Skip to content

Instantly share code, notes, and snippets.

@gustavorv86
Created March 28, 2019 11:49
Show Gist options
  • Save gustavorv86/de59dee62b62af414f257ca1ae924b14 to your computer and use it in GitHub Desktop.
Save gustavorv86/de59dee62b62af414f257ca1ae924b14 to your computer and use it in GitHub Desktop.
Python: execute a function with timeout using multiprocess
#!/usr/bin/env python
import sys
import multiprocessing
import time
def fn_loop_count(message, start_count, end_count):
for i in range(start_count, end_count):
print(message + ":" + str(i))
start_count +=1
time.sleep(1)
def exec_with_timeout(function_name, function_args, timeout):
p = multiprocessing.Process(target=function_name, args=function_args)
p.start()
p.join(timeout)
if p.is_alive():
p.terminate()
p.join()
return False
else:
return True
if __name__ == "__main__":
args = ("Hola Mundo", 10, 12, )
status = exec_with_timeout(fn_loop_count, args, 5)
print("Status: {}".format(status))
args = ("Hola Mundo", 10, 100, )
status = exec_with_timeout(fn_loop_count, args, 5)
print("Status: {}".format(status))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment