对python周期性定时器的示例详解
更新时间:2019年02月19日 15:41:57 作者:橘子or桔子
今天小编就为大家分享一篇对python周期性定时器的示例详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
一、用thread实现定时器
py_timer.py文件
#!/usr/bin/python #coding:utf-8 import threading import os import sys 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() def cancel(self): self.finished.set() def run(self): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) self.finished.set() class LoopTimer(_Timer): def __init__(self, interval, function, args=[], kwargs={}): _Timer.__init__(self, interval, function, args, kwargs) def run(self): while True: if not self.finished.is_set(): self.finished.wait(self.interval) self.function(*self.args, **self.kwargs) else: break def testlooptimer(): print("loop timer") if __name__ == '__main__': t = LoopTimer(3.0,testlooptimer) t.start()
二、 使用
import py_timer def serv_start(): #Perform first fork. try: thread_timer = py_timer.LoopTimer(timeout, start_timer) thread_timer.start() thread_timer.cancel() # except Exception, ex: print("daemon: %s %s", type(ex), ex) def start_timer(): print 'hello'
以上这篇对python周期性定时器的示例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
python操作音视频ffmpeg-python对比pyav选择
这篇文章主要介绍了python操作音视频的选择:ffmpeg-python对比pyav,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-11-11Django的ListView超详细用法(含分页paginate)
这篇文章主要介绍了Django的ListView超详细用法(含分页paginate),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-05-05
最新评论