A simple timer class encapsulated by threads in Python

From , 5 Years ago, written in Python, viewed 196 times.
URL https://pastebin.vip/view/1f9702db
  1. from threading import Timer
  2.  
  3. class MyTimer:
  4.        
  5.         def __init__(self):
  6.                 self._timer= None
  7.                 self._tm = None
  8.                 self._fn = None
  9.        
  10.         def _do_func(self):
  11.                 if self._fn:
  12.                         self._fn()
  13.                         self._do_start()
  14.  
  15.         def _do_start(self):
  16.                 self._timer = Timer(self._tm, self._do_func)
  17.                 self._timer.start()
  18.  
  19.         def start(self, tm, fn):
  20.                 self._fn = fn
  21.                 self._tm = tm
  22.                 self._do_start()
  23.  
  24.         def stop(self):
  25.                 try:
  26.                         self._timer.cancel()
  27.                 except:
  28.                         pass
  29.                        
  30. def hello():
  31.         from datetime import datetime
  32.         print("hello world!", datetime.now())
  33.  
  34.  
  35. if __name__ == '__main__':
  36.  
  37.         mt = MyTimer()
  38.         mt.start(2, hello)
  39.         for i in range(10):
  40.                 import time
  41.                 time.sleep(1)
  42.         mt.stop()
  43. #//python/6703

Reply to "A simple timer class encapsulated by threads in Python"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website