python通過(guò)線程實(shí)現(xiàn)定時(shí)器timer的方法
本文實(shí)例講述了python通過(guò)線程實(shí)現(xiàn)定時(shí)器timer的方法。分享給大家供大家參考。具體分析如下:
這個(gè)python類(lèi)實(shí)現(xiàn)了一個(gè)定時(shí)器效果,調(diào)用非常簡(jiǎn)單,可以讓系統(tǒng)定時(shí)執(zhí)行指定的函數(shù)
下面介紹以threading模塊來(lái)實(shí)現(xiàn)定時(shí)器的方法。
使用前先做一個(gè)簡(jiǎn)單試驗(yàn):
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()
運(yùn)行結(jié)果如下:
>python hello.py hello world hello world hello world
下面是定時(shí)器類(lèi)的實(shí)現(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()
以上代碼在Python 2.5.4中運(yùn)行通過(guò)
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python腳本操作Excel實(shí)現(xiàn)批量替換功能
這篇文章主要介紹了Python腳本操作Excel實(shí)現(xiàn)批量替換功能,本文使用的是Openpyxl工具,通過(guò)實(shí)例截圖給大家講解的非常詳細(xì),需要的朋友可以參考下2019-11-11docker django無(wú)法訪問(wèn)redis容器的解決方法
今天小編就為大家分享一篇docker django無(wú)法訪問(wèn)redis容器的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08Python文件監(jiān)聽(tīng)工具pyinotify與watchdog實(shí)例
今天小編就為大家分享一篇關(guān)于Python文件監(jiān)聽(tīng)工具pyinotify與watchdog實(shí)例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10Python實(shí)現(xiàn)比較撲克牌大小程序代碼示例
這篇文章主要介紹了Python實(shí)現(xiàn)比較撲克牌大小程序代碼示例,具有一定借鑒價(jià)值,需要的朋友可以了解下。2017-12-12Python3視頻轉(zhuǎn)字符動(dòng)畫(huà)的實(shí)例代碼
這篇文章主要介紹了Python3視頻轉(zhuǎn)字符動(dòng)畫(huà)的實(shí)例代碼,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08解決pip install xxx報(bào)錯(cuò)SyntaxError: invalid syntax的問(wèn)題
今天小編就為大家分享一篇解決pip install xxx報(bào)錯(cuò)SyntaxError: invalid syntax的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11使用優(yōu)化器來(lái)提升Python程序的執(zhí)行效率的教程
這篇文章主要介紹了使用優(yōu)化器來(lái)提升Python程序的執(zhí)行效率的教程,包括編寫(xiě)計(jì)時(shí)器和使用內(nèi)建的優(yōu)化器等,需要的朋友可以參考下2015-04-04