0

I have specific Task, I need know how long work some method in realtime. If some method work long I need raise Exception.

this is my test method:

@timer
    def get_mails(self):
        print("start method")
        max_sec1 = 7
        current_sec1 = 0

        while max_sec1 != current_sec1:
            time.sleep(1)
            current_sec1 += 1

        print("method is finish")

Bellow i write decorator, he controle how many times it work

class TickTack(threading.Thread):
    def __init__(self, func):
        super(TickTack, self).__init__()
        self._stop_event = threading.Event()
        self.func = func

    def run(self):
       self.run_function()

    def run_function(self):
        self.func(self)

    def terminate(self):
        self._stop_event.set()


def timer(func):

    @functools.wraps(func)
    def wrapper(*args):
        print("start wrapper")

        max_sec = 3 # max work sec
        current_sec = 0

        tick_tack_thread = TickTack(func)
        tick_tack_thread.start()

        while max_sec != current_sec:
            time.sleep(1)
            current_sec += 1
            print(current_sec)

        if max_sec == current_sec:
            tick_tack_thread.terminate() # stop thread!!! But it not work
            raise Exception("Method work so long")

        print("end wrapper")


    return wrapper

this code not stoped get_mails functions. But I need stoped(raise Exception some method(my case method get_mails ))

Cœur
  • 34,719
  • 24
  • 185
  • 251
nesalexy
  • 798
  • 1
  • 8
  • 28

0 Answers0