用Python编写简单的定时器的方法

作者:PandaraWen 时间:2022-03-15 07:20:32 

下面介绍以threading模块来实现定时器的方法。

首先介绍一个最简单实现:


import threading

def say_sth(str):
 print str
 t = threading.Timer(2.0, say_sth,[str])
 t.start()

if __name__ == '__main__':
 timer = threading.Timer(2.0,say_sth,['i am here too.'])
 timer.start()

不清楚在某些特殊应用场景下有什么缺陷否。

下面是所要介绍的定时器类的实现:


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
0
投稿

猜你喜欢

  • mysql免安装版配置步骤详解分享

    2024-01-22 08:18:07
  • Oracle生成单据编号存储过程的实例代码

    2024-01-23 19:10:19
  • 从web到内网渗透的一次过程详解

    2023-05-20 21:23:08
  • Python django导出excel详解

    2021-06-15 17:12:19
  • form表单的submit方法和submit事件

    2008-10-15 11:22:00
  • Python 用turtle实现用正方形画圆的例子

    2022-08-05 13:56:33
  • JavaScript中window.showModalDialog()用法详解

    2024-04-18 09:48:04
  • python机器学习MATLAB最小二乘法的两种解读

    2022-02-19 08:00:11
  • JavaScript中call,apply,bind的区别与实现

    2024-04-22 12:51:26
  • Python 日志logging模块用法简单示例

    2021-10-08 19:47:20
  • 验证码的最高境界

    2008-05-08 14:17:00
  • 利用Python为iOS10生成图标和截屏

    2021-05-03 11:15:09
  • SQLserver 数据库危险存储过程删除与恢复方法

    2011-09-30 11:33:54
  • python实现word文档批量转成自定义格式的excel文档的思路及实例代码

    2022-05-31 14:22:04
  • SQL语句实现查询当前数据库IO等待状况

    2024-01-17 02:04:32
  • Django瀑布流的实现示例

    2021-05-09 10:07:42
  • GPU版本安装Pytorch的最新方法步骤

    2022-02-09 16:31:28
  • PyQt5 PySide2 触摸测试功能的实现代码

    2022-06-23 22:22:25
  • MySQL Where 条件语句介绍和运算符小结

    2024-01-12 13:17:43
  • mysql 5.7更改数据库的数据存储位置的解决方法

    2024-01-21 11:56:43
  • asp之家 网络编程 m.aspxhome.com