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

相关文章

python 不同方式读取文件速度不同的实例

1、按行读取较慢较耗时: srcFiles = open('inputFile.txt', 'r') for file_path in srcFiles: file_path...

selenium+python自动化测试之环境搭建

selenium+python自动化测试之环境搭建

最近由于公司有一个向谷歌网站上传文件的需求,需要进行web的自动化测试,选择了selenium这个自动化测试框架,以前没有接触过这门技术,所以研究了一下,使用python来实现自动化脚本...

pytorch 利用lstm做mnist手写数字识别分类的实例

代码如下,U我认为对于新手来说最重要的是学会rnn读取数据的格式。 # -*- coding: utf-8 -*- """ Created on Tue Oct 9 08:53:25...

Python运行报错UnicodeDecodeError的解决方法

Python2.7在Windows上有一个bug,运行报错: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in...

pygame 精灵的行走及二段跳的实现方法(必看篇)

pygame 精灵的行走及二段跳的实现方法(必看篇)

不得不承认《Python游戏编程入门》这本书翻译、排版非常之烂,但是里面的demo还是很好的,之前做了些改编放到这里。 先是素材: 背景 精灵 所有素材均取自此书 接下来就是精灵类的...