python通过线程实现定时器timer的方法_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
, 线程
, 定时器
, 方法
timer
python 定时器 timer、python 多线程定时器、linux线程定时器实现、python实现多线程、python 线程池实现,以便于您获取更多的相关知识。

时间: 2024-08-31 01:43:55

python通过线程实现定时器timer的方法_python的相关文章

python使用装饰器和线程限制函数执行时间的方法_python

本文实例讲述了python使用装饰器和线程限制函数执行时间的方法.分享给大家供大家参考.具体分析如下: 很多时候函数内部包含了一些不可预知的事情,比如调用其它软件,从网络抓取信息,可能某个函数会卡在某个地方不动态,这段代码可以用来限制函数的执行时间,只需要在函数的上方添加一个装饰器,timelimited(2)就可以限定函数必须在2秒内执行完成,如果执行完成则返回函数正常的返回值,如果执行超时则会抛出错误信息. # -*- coding: utf-8 -*- from threading imp

python实现根据窗口标题调用窗口的方法_python

本文实例讲述了python实现根据窗口标题调用窗口的方法.分享给大家供大家参考.具体分析如下: 当你知道一个windows窗口的标题后,可以用下面的代码调用窗口,甚至向窗口内写入内容. #-*-coding:utf-8-*- import win32gui,win32con #下面的是窗口的标题名称,这样是一定错的,但在控制台就可以正常使用 #写在文件里要用U编码 a=u"jb51.net" dlg=win32gui.FindWindow(None,a) //用控件的ID取得控件的句柄

Python解析xml中dom元素的方法_python

本文实例讲述了Python解析xml中dom元素的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: from xml.dom import minidom try:     xmlfile = open("path.xml", "a+")     #xmldoc = minidom.parse( sys.argv[1])     xmldoc = minidom.parse(xmlfile) except :     #updatelogger.

Python实现去除代码前行号的方法_python

本文实例讲述了Python实现去除代码前行号的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: # -*- coding: utf-8 -*- import wx class MainWindow(wx.Frame):     def __init__(self, parent, id):         wx.Frame.__init__(self, parent, id,         u'去除代码前行号的Python小工具 - wxPython版 - Develop

python检测远程端口是否打开的方法_python

本文实例讲述了python判断远程端口是否打开的方法.分享给大家供大家参考.具体实现方法如下: import socket sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk.settimeout(1) try: sk.connect(('www.sharejs.com',80)) print 'Server port 80 OK!' except Exception: print 'Server port 80 not conne

python检测远程服务器tcp端口的方法_python

本文实例讲述了python检测远程服务器tcp端口的方法.分享给大家供大家参考.具体如下: python检测远程服务器tcp端口的代码,这段代码可以用来做服务器监控实用 #!/usr/bin/env python #coding:utf-8 #filename:tcp.py ''' author: gavingeng date: 2011-12-14 09:35:59 ''' import socket import sys NORMAL=0 ERROR=1 TIMEOUT=5 def ping

python实现超简单端口转发的方法_python

本文实例讲述了python实现超简单端口转发的方法.分享给大家供大家参考.具体如下: 代码非常简单,实现了简单的端口数据转发功能,用于真实环境还需要再修改一下. 复制代码 代码如下: #tcp server import socket host = '127.0.0.1'          #Local Server IP host2 = '127.0.0.1'   #Real Server IP port = 6001 #Local Server Port port2 = 7001 #Real

python简单程序读取串口信息的方法_python

本文实例讲述了python简单程序读取串口信息的方法.分享给大家供大家参考.具体分析如下: 这段代码需要调用serial模块,通过while循环不断读取串口数据 import time import serial ser = serial.Serial( #下面这些参数根据情况修改 port='COM1', baudrate=9600, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO, bytesize=serial.SEVENBIT

python使用chardet判断字符串编码的方法_python

本文实例讲述了python使用chardet判断字符串编码的方法.分享给大家供大家参考.具体分析如下: 最近利用python抓取一些网上的数据,遇到了编码的问题.非常头痛,总结一下用到的解决方案. linux中vim下查看文件编码的命令 set fileencoding python中一个强力的编码检测包 chardet ,使用方法非常简单.linux下利用pip install chardet实现简单安装 import chardet f = open('file','r') fencodin