对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 将字符串转换成字典dict

复制代码 代码如下:JSON到字典转化:dictinfo = simplejson.loads(json_str) 输出dict类型 字典到JSON转化:jsoninfo = simpl...

使用Python中的tkinter模块作图的方法

使用Python中的tkinter模块作图的方法

python简述: Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。自从20世纪90年代初Python语言诞生至今,它逐渐被广泛应用于处理系统管理任务和Web编程。P...

Python实现PS图像调整之对比度调整功能示例

Python实现PS图像调整之对比度调整功能示例

本文实例讲述了Python实现PS图像调整之对比度调整功能。分享给大家供大家参考,具体如下: 这里用 Python 实现 PS 里的图像调整–对比度调整。具体的算法原理如下: (1)、n...

python针对不定分隔符切割提取字符串的方法

问题:我们需要在散沙一般的数据中提取出字符,分隔符不止一个,而且还有不少空格,比如: 原字符串如下: 'asd ff gg; asd , foo| og ' 我们需要删除上面的,;...

python+POP3实现批量下载邮件附件

最近新开学,接到了给老板的本科课程当助教的工作,百十来号人一学期下来得有四五次作业发进邮箱里,需要我来统计打分,想想挨个点进去下载附件的过程就头大,于是萌生了写个脚本来统计作业的想法。...