一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - python通過線程實現定時器timer的方法

python通過線程實現定時器timer的方法

2019-12-03 14:31chongq Python

這篇文章主要介紹了python通過線程實現定時器timer的方法,涉及Python線程與定時器timer的使用技巧,需要的朋友可以參考下

本文實例講述了python通過線程實現定時器timer的方法。分享給大家供大家參考。具體分析如下:

這個python類實現了一個定時器效果,調用非常簡單,可以讓系統定時執行指定的函數

下面介紹以threading模塊來實現定時器的方法。

使用前先做一個簡單試驗:

  1. import threading 
  2. def sayhello(): 
  3.     print "hello world" 
  4.     global t    #Notice: use global variable! 
  5.     t = threading.Timer(5.0, sayhello) 
  6.     t.start() 
  7. t = threading.Timer(5.0, sayhello) 
  8. t.start() 

運行結果如下:

  1. >python hello.py 
  2. hello world 
  3. hello world 
  4. hello world 

下面是定時器類的實現:

  1. class Timer(threading.Thread): 
  2.     ""
  3.     very simple but useless timer. 
  4.     ""
  5.     def __init__(self, seconds): 
  6.         self.runTime = seconds 
  7.         threading.Thread.__init__(self) 
  8.     def run(self): 
  9.         time.sleep(self.runTime) 
  10.         print "Buzzzz!! Time's up!" 
  11. class CountDownTimer(Timer): 
  12.     ""
  13.     a timer that can counts down the seconds. 
  14.     ""
  15.     def run(self): 
  16.         counter = self.runTime 
  17.         for sec in range(self.runTime): 
  18.             print counter 
  19.             time.sleep(1.0) 
  20.             counter -= 1 
  21.         print "Done" 
  22. class CountDownExec(CountDownTimer): 
  23.     ""
  24.     a timer that execute an action at the end of the timer run. 
  25.     ""
  26.     def __init__(self, seconds, action, args=[]): 
  27.         self.args = args 
  28.         self.action = action 
  29.         CountDownTimer.__init__(self, seconds) 
  30.     def run(self): 
  31.         CountDownTimer.run(self) 
  32.         self.action(self.args) 
  33. def myAction(args=[]): 
  34.     print "Performing my action with args:" 
  35.     print args 
  36. if __name__ == "__main__"
  37.     t = CountDownExec(3, myAction, ["hello""world"]) 
  38.     t.start() 

以上代碼在Python 2.5.4中運行通過

希望本文所述對大家的Python程序設計有所幫助。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 22sihu国产精品视频影视资讯 | 亚洲精品一区二区三区中文字幕 | 蜜桃88av| 国产精品网页 | 草莓视频首页 | 成年女人免费 | 色呦阁 | 67194最新网址 | 婷婷在线观看香蕉五月天 | 幻女free性摘花第一次 | 国产最新精品视频 | 成年人免费在线看的惊悚动作片 | 亚洲小视频 | 国产精品污双胞胎在线观看 | 天天干天天操天天爽 | 国产高清一区二区三区免费视频 | 久久精品视在线观看85 | 大奶妈咪女教师 | 久久免费国产视频 | 毛片手机在线视频免费观看 | 色婷婷在线播放 | 黑人巨茎大战欧美白妇 | 脱了白丝校花的内裤猛烈进入 | 四虎影院精品在线观看 | 秋霞理论在一l级毛片 | 日韩av线观看 | 国产亚洲精aa在线观看香蕉 | 国产亚洲精品一区久久 | 亚欧洲乱码视频一二三区 | 天海翼三级 | 女人扒开下面让男人桶爽视频 | 亚洲va在线va天堂va偷拍 | 国产一区二区在线观看视频 | 99在线观看免费视频 | 国产夜趣福利第一视频 | 韩国靠逼 | 日韩一级生活片 | 91香蕉在线 | 雪恋电影完整版免费观看 | 爽爽窝窝午夜精品一区二区 | 国产精品女主播大秀在线 |