对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简单生成随机数的方法示例

本文实例讲述了Python简单生成随机数的方法。分享给大家供大家参考,具体如下: 主要知识点: 随机整数: random.randint(a,b):返回随机整数x,a<=x<...

Python中xml和dict格式转换的示例代码

在做接口自动化的时候,请求数据之前都是JSON格式的,Python有自带的包来解决。最近在做APP的接口,遇到XML格式的请求数据,费了很大劲来解决,解决方式是:接口文档拿到的是XML,...

K-近邻算法的python实现代码分享

K-近邻算法的python实现代码分享

k-近邻算法概述: 所谓k-近邻算法KNN就是K-Nearest neighbors Algorithms的简称,它采用测量不同特征值之间的距离方法进行分类 用官方的话来说,所谓K近邻...

Python同时向控制台和文件输出日志logging的方法

本文实例讲述了Python同时向控制台和文件输出日志logging的方法。分享给大家供大家参考。具体如下: python提供了非常方便的日志模块,可实现同时向控制台和文件输出日志的功能。...

使用python绘制3维正态分布图的方法

使用python绘制3维正态分布图的方法

今天使用python画了几个好玩的3D展示图,现在分享给大家。 先贴上图片 使用的python工具包为: from matplotlib import pyplot as pl...