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程序设计有所帮助。

相关文章

50行代码实现贪吃蛇(具体思路及代码)

50行代码实现贪吃蛇(具体思路及代码)

最近一直在准备用来面试的几个小demo,为了能展现自己,所以都是亲自设计并实现的,其中一个就是在50行代码内来实现一个贪吃蛇,为了说明鄙人自己练习编程的一种方式--把代码写短,为了理解语...

在notepad++中实现直接运行python代码

在notepad++中实现直接运行python代码

Notepad++ 是一款非常有特色的编辑器,软件小巧高效,支持27种编程语言,通吃C,C++ ,Java ,C#, XML, HTML, PHP,JS,python 等。是程序员必备开...

详解【python】str与json类型转换

在写接口测试框架时。避免不了数据类型的转换,比如强制转换string类型,比如转json类型 str转json python字符串转json对象,需要使用json模块的loads函数...

python plotly画柱状图代码实例

python plotly画柱状图代码实例

这篇文章主要介绍了python plotly画柱状图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 代码 import p...

Python探索之自定义实现线程池

为什么需要线程池呢?         设想一下,如果我们使用有任务就开启一个子线程处理,处理完成后,销毁子线程或等...