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

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

相关文章

分享Pycharm中一些不为人知的技巧

分享Pycharm中一些不为人知的技巧

工欲善其事必先利其器,Pycharm 是最受欢迎的Python开发工具,它提供的功能非常强大,是构建大型项目的理想工具之一,如果能挖掘出里面实用技巧,能带来事半功倍的效果。 以下操作都是...

Python中使用Beautiful Soup库的超详细教程

Python中使用Beautiful Soup库的超详细教程

1. Beautiful Soup的简介 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下:    ...

Python开发之快速搭建自动回复微信公众号功能

Python开发之快速搭建自动回复微信公众号功能

在之前的一篇文章 Python利用 AIML 和 Tornado 搭建聊天机器人微信订阅号 中用 aiml 实现了一个简单的英文聊天机器人订阅号。但是只能处理英文消息,现在用 图灵机器人...

python实现矩阵打印

python实现矩阵打印

本文实例为大家分享了python实现矩阵打印的具体代码,供大家参考,具体内容如下 之前面试嵌入式软件的一道题,用c实现矩阵打印,考场上并没有写出来,之后总感觉自己写不出来也就没有去实现,...

解决python执行不输出系统命令弹框的问题

最近做一个的GUI,因为调用了os模块里的system方法,使用pyinstaller打包的时候选择不输出系统命令弹框,程序无法运行,要求要有系统命令框。在网上找到一个解决办法。使用su...