欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-20 10:35:32
一、用thread实现定时器 py_timer.py文件 #!/usr/bin/python #coding:utf-8 import threadin...

一、用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周期性定时器的示例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。