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程序设计有所帮助。

相关文章

解决Python3用PIL的ImageFont输出中文乱码的问题

解决Python3用PIL的ImageFont输出中文乱码的问题

今天在用python3+ImageFont输出中文时,结果显示乱码 # coding:utf-8 from PIL import Image, ImageDraw, ImageFon...

Python获取DLL和EXE文件版本号的方法

本文实例讲述了Python获取DLL和EXE文件版本号的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:import win32api def getFileVers...

Python遍历pandas数据方法总结

Python遍历pandas数据方法总结

前言 Pandas是python的一个数据分析包,提供了大量的快速便捷处理数据的函数和方法。其中Pandas定义了Series 和 DataFrame两种数据类型,这使数据操作变得更简...

python ElementTree 基本读操作示例

示例可以附件中下载 1.加载xml文件 加载XML文件共有2种方法,一是加载指定字符串,二是加载指定文件 2.获取element的方法 a) 通过getiterator b) 过 get...

对Python中class和instance以及self的用法详解

一. Python 的类和实例 在面向对象中,最重要的概念就是类(class)和实例(instance),类是抽象的模板,而实例是根据类创建出来的一个个具体的 “对象”。 就好比,学生是...