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

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

相关文章

使用python实现希尔、计数、基数基础排序的代码

使用python实现希尔、计数、基数基础排序的代码

希尔排序 希尔排序是一个叫希尔的数学家提出的一种优化版本的插入排序。 首先取一个整数d1=n//2,将元素分为d1个组,每组相邻元素之间的距离为d1,在各组内进行直接插入排序。 取第二个...

Python应用库大全总结

学Python,想必大家都是从爬虫开始的吧。毕竟网上类似的资源很丰富,开源项目也非常多。 Python学习网络爬虫主要分3个大的版块:抓取,分析,存储 当我们在浏览器中输入一个url后回...

Python操作word常见方法示例【win32com与docx模块】

本文实例讲述了Python操作word常见方法。分享给大家供大家参考,具体如下: 这里介绍两种方式: 使用win32com 使用docx 1. 使用win32com扩展包 只...

Centos5.x下升级python到python2.7版本教程

首先到官网下载python2.7.3版本,编译安装 复制代码 代码如下: $wget http://www.python.org/ftp/python/2.7.3/Python-2.7....

使用Python获取Linux系统的各种信息

在本文中,我们将会探索使用Python编程语言工具来检索Linux系统各种信息。走你。 哪个Python版本? 当我提及Python,所指的就是CPython 2(准确的是2.7...