对python周期性定时器的示例详解

yipeiwu_com6年前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设计】。

相关文章

Python获取指定文件夹下的文件名的方法

本文采用os.walk()和os.listdir()两种方法,获取指定文件夹下的文件名。 一、os.walk() 模块os中的walk()函数可以遍历文件夹下所有的文件。 os.wa...

TensorFlow 实战之实现卷积神经网络的实例讲解

本文根据最近学习TensorFlow书籍网络文章的情况,特将一些学习心得做了总结,详情如下.如有不当之处,请各位大拿多多指点,在此谢过。 一、相关性概念 1、卷积神经网络(Convolu...

Python使用Flask框架获取当前查询参数的方法

本文实例讲述了Python使用Flask框架获取当前查询参数的方法。分享给大家供大家参考。具体如下: 这段代码实现Python的Flask框架下获取当前查询参数,即QueryString...

用Django实现一个可运行的区块链应用

用Django实现一个可运行的区块链应用

对数字货币的崛起感到新奇的我们,并且想知道其背后的技术——区块链是怎样实现的。   但是完全搞懂区块链并非易事,我喜欢在实践中学习,通过写代码来学习技术会掌握得更牢固。通过构建...

python多个模块py文件的数据共享实例

模块a.py 想用 b.py中公有数据 cnt b的python文件 #!/usr/bin/env python # coding:utf8 from wx import Cal...