今天看網絡框架時,突然想看一下定時器,於是往上搜索了一下python中timer task的實現,但是由於python本身對線程的支持不是太好,因為全局排它鎖的存在,使得多線程在訪問資源時效率比較低。下面來提一下網上普遍使用的timer類的thread實現方法。
#-*-coding:utf-8-*- import threading def doTask(): print 'hello' timer=threading.Timer(1,doTask) timer.start()
輸出結果:
hello
既然是定時任務,為什么不循環執行呢?
因為代碼只執行了一遍,怎么可能輸出多行!
改一下就OK了:
#-*-coding:utf-8-*- import threading def doTask(): print 'hello\n' if __name__=='__main__': while True: timer=threading.Timer(1,doTask) timer.start()
不過這是一個死循環。很不好,另一種笨笨方法:
#-*-coding:utf-8-*- import threading from time import sleep def doTask(): print 'hello\n' timer=threading.Timer(1,doTask) timer.start() timer=threading.Timer(1,doTask) timer.start()
本人不推薦這么使用定時,下面來介紹一些第三方中的定時任務類:Twisted中的Task.
from twisted.internet import task import logging class MyTimeTask(object): def __init__(self): self.taskName='task' def myPrint(self): print self.taskName def onTime(self): try: self.myPrint() except Exception: logging.error('print fasiled!') def starTask(self): temp=task.LoopingCall(self.onTime) temp.start(1, True) instance=MyTimeTask() instance.starTask()
框架定時任務完畢。謝謝閱讀