From d63a455d393c3c42523095aa400ca0500e1bdc13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Volkan=20=C5=9Eahin?= Date: Fri, 22 Jul 2016 10:33:45 +0300 Subject: [PATCH] timer method added for using with some specific function which need timeout actions --- opt/ahenk/base/timer/setup_timer.py | 8 +++++ opt/ahenk/base/timer/timer.py | 52 +++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 opt/ahenk/base/timer/setup_timer.py create mode 100644 opt/ahenk/base/timer/timer.py diff --git a/opt/ahenk/base/timer/setup_timer.py b/opt/ahenk/base/timer/setup_timer.py new file mode 100644 index 0000000..c70a1f2 --- /dev/null +++ b/opt/ahenk/base/timer/setup_timer.py @@ -0,0 +1,8 @@ +from multiprocessing import Process + + +class SetupTimer: + @staticmethod + def start(timer): + thread_timer = Process(target=timer.run) + thread_timer.start() diff --git a/opt/ahenk/base/timer/timer.py b/opt/ahenk/base/timer/timer.py new file mode 100644 index 0000000..43a7ede --- /dev/null +++ b/opt/ahenk/base/timer/timer.py @@ -0,0 +1,52 @@ +import time + + +class Timer: + def __init__(self, timeout, timeout_function, checker_func=None, checker_success_function=None, **kwargs): + self.timeout = int(timeout) + self.timeout_function = timeout_function + self.timeout_function_args = None + self.checker_func_args = None + self.checker_success_function_args = None + + if kwargs is not None and kwargs['kwargs'] is not None: + if 'timeout_args' in kwargs['kwargs']: + self.timeout_function_args = kwargs['kwargs']['timeout_args'] + + if 'checker_args' in kwargs['kwargs']: + self.checker_func_args = kwargs['kwargs']['checker_args'] + + if 'success_args' in kwargs['kwargs']: + self.checker_success_function_args = kwargs['kwargs']['success_args'] + + self.checker_func = checker_func + self.checker_success_function = checker_success_function + + def run_function(self, function, parameter=None): + if function is not None: + if parameter is None: + function() + else: + function(parameter) + + def run(self): + timer = self.timeout + + while timer > 0: + + if self.checker_func is not None: + if self.checker_func_args is not None: + if self.checker_func(self.checker_func_args) is True: + self.run_function(self.checker_success_function, self.checker_success_function_args) + return + else: + if self.checker_func() is True: + self.run_function(self.checker_success_function, self.checker_success_function_args) + return + + time.sleep(1) + timer -= 1 + if self.timeout_function_args is not None: + self.timeout_function(self.timeout_function_args) + else: + self.timeout_function()