python通过线程实现定时器timer的方法

yipeiwu_com5年前Python基础

本文实例讲述了python通过线程实现定时器timer的方法。分享给大家供大家参考。具体分析如下:

这个python类实现了一个定时器效果,调用非常简单,可以让系统定时执行指定的函数

下面介绍以threading模块来实现定时器的方法。

使用前先做一个简单试验:

import threading
def sayhello():
    print "hello world"
    global t    #Notice: use global variable!
    t = threading.Timer(5.0, sayhello)
    t.start()
t = threading.Timer(5.0, sayhello)
t.start()

运行结果如下:

>python hello.py
hello world
hello world
hello world

下面是定时器类的实现:

class Timer(threading.Thread):
    """
    very simple but useless timer.
    """
    def __init__(self, seconds):
        self.runTime = seconds
        threading.Thread.__init__(self)
    def run(self):
        time.sleep(self.runTime)
        print "Buzzzz!! Time's up!"
class CountDownTimer(Timer):
    """
    a timer that can counts down the seconds.
    """
    def run(self):
        counter = self.runTime
        for sec in range(self.runTime):
            print counter
            time.sleep(1.0)
            counter -= 1
        print "Done"
class CountDownExec(CountDownTimer):
    """
    a timer that execute an action at the end of the timer run.
    """
    def __init__(self, seconds, action, args=[]):
        self.args = args
        self.action = action
        CountDownTimer.__init__(self, seconds)
    def run(self):
        CountDownTimer.run(self)
        self.action(self.args)
def myAction(args=[]):
    print "Performing my action with args:"
    print args
if __name__ == "__main__":
    t = CountDownExec(3, myAction, ["hello", "world"])
    t.start()

以上代码在Python 2.5.4中运行通过

希望本文所述对大家的Python程序设计有所帮助。

相关文章

对python numpy.array插入一行或一列的方法详解

如下所示: import numpy as np a = np.array([[1,2,3],[4,5,6],[7,8,9]]) b = np.array([[0,0,0]]) c...

Python Opencv提取图片中某种颜色组成的图形的方法

Python Opencv提取图片中某种颜色组成的图形的方法

主要目标识别图中红色的裂缝,尝试了几种不同的方法,最后发现比较每一点的RGB差值可以很好的解决这个问题,也就是提取图片中的红色相关信息。处理结果如下: 实现的代码如下,注意openc...

Python获取系统默认字符编码的方法

本文实例讲述了Python获取系统默认字符编码的方法。分享给大家供大家参考。具体分析如下: 在Python代码中,普通字符串的编码方式与程序源文件编码方式一致的,而很多IDE在默认情况下...

python修改注册表终止360进程实例

本文实例讲述了python修改注册表终止360进程的实现方法。分享给大家供大家参考。 具体实现代码如下: import _winreg import os import shutil...

Python编写一个闹钟功能

音频文件放入和.py文件同级的目录下 import winsound # 导入此模块实现声音播放功能 import time # 导入此模块,获取当前时间 # 提示用户设置时间和分钟...