对python周期性定时器的示例详解
一、用thread实现定时器
py_timer.py文件
#!/usr/bin/python
#coding:utf-8
importthreading
importos
importsys
class_Timer(threading.Thread):
def__init__(self,interval,function,args=[],kwargs={}):
threading.Thread.__init__(self)
self.interval=interval
self.function=function
self.args=args
self.kwargs=kwargs
self.finished=threading.Event()
defcancel(self):
self.finished.set()
defrun(self):
self.finished.wait(self.interval)
ifnotself.finished.is_set():
self.function(*self.args,**self.kwargs)
self.finished.set()
classLoopTimer(_Timer):
def__init__(self,interval,function,args=[],kwargs={}):
_Timer.__init__(self,interval,function,args,kwargs)
defrun(self):
whileTrue:
ifnotself.finished.is_set():
self.finished.wait(self.interval)
self.function(*self.args,**self.kwargs)
else:
break
deftestlooptimer():
print("looptimer")
if__name__=='__main__':
t=LoopTimer(3.0,testlooptimer)
t.start()
二、使用
importpy_timer
defserv_start():
#Performfirstfork.
try:
thread_timer=py_timer.LoopTimer(timeout,start_timer)
thread_timer.start()
thread_timer.cancel()#
exceptException,ex:
print("daemon:%s%s",type(ex),ex)
defstart_timer():
print'hello'
以上这篇对python周期性定时器的示例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
热门推荐
7 简短的二胎祝福语
10 简短霸气女儿生日 祝福语
11 祝福语高考小众诗句简短
12 元旦祝福语20秒简短
13 老师过年祝福语大全 简短
14 一生祝福语简短
15 产检祝福语简短霸气
16 朋友店开张祝福语简短
17 生日爱情祝福语大全简短
18 朋友女儿生日祝福语 简短