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之用Python计算

一提到计算机,当然现在更多人把她叫做电脑,这两个词都是指computer。不管什么,只要提到她,普遍都会想到她能够比较快地做加减乘除,甚至乘方开方等。乃至于,有的人在口语中区分不开计算机...

python如何制作缩略图

python如何制作缩略图

本文实例为大家分享了python制作缩略图的具体代码,供大家参考,具体内容如下 import cv2 #导入opencv模块 from tkinter import * #导入tki...

解决pandas展示数据输出时列名不能对齐的问题

列名用了中文的缘故,设置pandas的参数即可, 代码如下: import pandas as pd #这两个参数的默认设置都是False pd.set_option('dis...

Python实现的计数排序算法示例

Python实现的计数排序算法示例

本文实例讲述了Python实现的计数排序算法。分享给大家供大家参考,具体如下: 计数排序是一种非常快捷的稳定性强的排序方法,时间复杂度O(n+k),其中n为要排序的数的个数,k为要排序的...

Python通过TensorFlow卷积神经网络实现猫狗识别

这份数据集来源于Kaggle,数据集有12500只猫和12500只狗。在这里简单介绍下整体思路 处理数据 设计神经网络 进行训练测试 1. 数据处理 将图片数据处理为 t...