国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

用Python編寫簡單的定時器的方法

2019-11-25 17:34:15
字體:
供稿:網(wǎng)友

下面介紹以threading模塊來實現(xiàn)定時器的方法。

首先介紹一個最簡單實現(xiàn):

import threadingdef 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()

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

下面是所要介紹的定時器類的實現(xiàn):

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() 

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 香港| 康保县| 梁山县| 中卫市| 沾化县| 望都县| 大港区| 望都县| 若尔盖县| 河池市| 石景山区| 张家界市| 乌兰浩特市| 巴彦淖尔市| 万源市| 乐亭县| 景德镇市| 三台县| 巴林左旗| 广宁县| 仁布县| 三原县| 库伦旗| 湖口县| 奉贤区| 集安市| 西吉县| 榆林市| 大英县| 东光县| 绵竹市| 饶阳县| 蓬莱市| 武功县| 广宗县| 桓台县| 镶黄旗| 马龙县| 临桂县| 孝昌县| 泰宁县|