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

作者:chongq 时间:2023-04-28 17:49:28 

本文实例讲述了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,线程,定时器
0
投稿

猜你喜欢

  • Python3使用TCP编写一个简易的文件下载器功能

    2021-02-20 09:58:07
  • python使用openpyxl库读写Excel表格的方法(增删改查操作)

    2021-11-29 01:22:43
  • jdbc操作mysql数据库实例

    2024-01-26 01:59:50
  • python 机器学习之支持向量机非线性回归SVR模型

    2022-06-17 20:23:55
  • Python判断字符串与大小写转换

    2021-07-17 03:23:35
  • Python强大的自省机制详解

    2021-06-07 02:07:57
  • python批量读取文件名并写入txt文件中

    2021-02-18 16:32:29
  • python内打印变量之%和f的实例

    2021-06-19 07:46:46
  • go语言K8S 的 informer机制浅析

    2024-05-13 10:44:51
  • 微信小程序实现登录注册tab切换效果

    2024-04-29 13:11:29
  • MySQL 表字段属性

    2011-09-10 16:01:01
  • Python使用itchat 功能分析微信好友性别和位置

    2023-09-24 15:57:12
  • MySQL常用命令大全脚本之家总结

    2024-01-15 06:13:13
  • Python中动态创建类实例的方法

    2023-07-20 02:36:44
  • 使用Selenium实现微博爬虫(预登录、展开全文、翻页)

    2022-07-09 11:00:18
  • PHP utf-8编码问题,utf8编码,数据库乱码,页面显示输出乱码

    2024-04-30 09:57:47
  • Idea开发工具之SpringBoot整合JSP的过程

    2023-06-14 19:50:23
  • Python就将所有的英文单词首字母变成大写

    2023-09-21 10:44:35
  • 几款黑体的测试和介绍

    2008-07-18 17:09:00
  • Oracle数据库系统使用经验六则

    2010-07-26 13:22:00
  • asp之家 网络编程 m.aspxhome.com