[Python] python用线程封装的一个简单的定时器类 →→→→→进入此内容的聊天室

来自 , 2019-02-21, 写在 Python, 查看 152 次.
URL http://www.code666.cn/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

回复 "python用线程封装的一个简单的定时器类"

这儿你可以回复上面这条便签

captcha