对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使用PyCrypto实现AES加密功能示例

本文实例讲述了Python使用PyCrypto实现AES加密功能。分享给大家供大家参考,具体如下: #!/usr/bin/env python from Crypto.Cipher...

python读取并写入mat文件的方法

先给大家介绍下python读取并写入mat文件的方法 用matlab生成一个示例mat文件: clear;clc matrix1 = magic(5); matrix2 = magi...

用tensorflow实现弹性网络回归算法

本文实例为大家分享了tensorflow实现弹性网络回归算法,供大家参考,具体内容如下 python代码: #用tensorflow实现弹性网络算法(多变量) #使用鸢尾花数据集,...

python更改已存在excel文件的方法

需要用到的包: import xlrd import xlwt import xlutils 修改已经存在的excel文件的思路: 首先,将需要更改的excel文件打开,用...

python输出带颜色字体实例方法

python输出带颜色字体实例方法

在python开发的过程中,经常会遇到需要打印各种信息。海量的信息堆砌在控制台中,就会导致信息都混在一起,降低了重要信息的可读性。这时候,如果能给重要的信息加上字体颜色,那么就会更加方便...