python使用线程封装的一个简单定时器类实例

yipeiwu_com6年前Python基础

本文实例讲述了python使用线程封装的一个简单定时器类。分享给大家供大家参考。具体实现方法如下:

from threading import Timer
class MyTimer:
 def __init__(self):
 self._timer= None
 self._tm = None
 self._fn = None
 def _do_func(self):
 if self._fn:
  self._fn()
  self._do_start()
 def _do_start(self):
 self._timer = Timer(self._tm, self._do_func)
 self._timer.start()
 def start(self, tm, fn):
 self._fn = fn
 self._tm = tm
 self._do_start()
 def stop(self):
 try:
  self._timer.cancel()
 except:
  pass
def hello():
 from datetime import datetime
 print("hello world!", datetime.now())
if __name__ == '__main__':
 mt = MyTimer()
 mt.start(2, hello)
 for i in range(10):
 import time
 time.sleep(1)
 mt.stop()

希望本文所述对大家的Python程序设计有所帮助。

相关文章

为何人工智能(AI)首选Python?读完这篇文章你就知道了(推荐)

为何人工智能(AI)首选Python?读完这篇文章你就知道了(推荐)

为何人工智能(AI)首选Python?读完这篇文章你就知道了。我们看谷歌的TensorFlow基本上所有的代码都是C++和Python,其他语言一般只有几千行 。如果讲运行速度的部分,...

python从入门到精通(DAY 2)

1、字典复制: dict = {'name':'wang', 'sex':'m', 'age':34, 'job':'it'} info = dict ##别名 (二个字...

python 使用pandas计算累积求和的方法

使用pandas下的cumsum函数 cumsum:计算轴向元素累积加和,返回由中间结果组成的数组.重点就是返回值是"由中间结果组成的数组" import numpy as np '...

Python-Tkinter Text输入内容在界面显示的实例

使用Tkinter(py2.7)text文本框中输入内容在界面中显示–较为规整的代码: import Tkinter as tk class Window: def __init...

python版本的读写锁操作方法

本文实例讲述了python版本的读写锁操作方法。分享给大家供大家参考,具体如下: 最近要用到读写锁的机制,但是python2.7的自带库里居然木有. 网上讲读写锁的例子众多,但是原理简单...