Skip to content
Watchdog.py 1.15 KiB
Newer Older
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 24 20:15:09 2021

@author: oem
"""


#!/usr/bin/python
# file: watchdog.py
# license: MIT License

import signal
import time
import random

class Watchdog(Exception):
    def __init__(self, time=5):
        self.time = time
  
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handler)
        signal.alarm(self.time)
  
    def __exit__(self, type, value, traceback):
        signal.alarm(0)
    
    def handler(self, signum, frame):
        raise self
  
    def __str__(self):
        return "The code you executed took more than %ds to complete" % self.time


# import the class
#from watchdog import Watchdog

def long_function():
    r = random.random()
    print(f'random: {r}')
    t_rand = 2*r
    
    
    time.sleep(t_rand)
    return t_rand

# don't allow long_function to take more than 5 seconds to complete
    
tiempos = []

for i in range(10):
    try:
        with Watchdog(1):
            t0 = long_function()
            print(t0)
            tiempos.append(t0)
    except Watchdog:
        print("long_function() took too long to complete")
        tiempos.append(0)