• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

python如何使用线程实现定时器timer的代码

python 水墨上仙 1516次浏览

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

代码转自:http://blog.chinaunix.net/uid-15007890-id-106979.html

下面介绍以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&nbsp2.5.4中运行通过


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


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明python如何使用线程实现定时器timer的代码
喜欢 (0)
加载中……