2015-04-21 30 views

回答

6

使用一個線程包含循環

from threading import Thread 
import time 

def background_task(): 
    while not background_task.cancelled: 
     self.mqConn.heartbeat_tick() 
     time.sleep(30) 
background_task.cancelled = False 

t = Thread(target=background_task) 
t.start() 

background_task.cancelled = True 

或者,你可以繼承定時器,使取消簡單:

from threading import Timer 

class RepeatingTimer(Timer): 
    def run(self): 
     while not self.finished.is_set(): 
      self.function(*self.args, **self.kwargs) 
      self.finished.wait(self.interval) 


t = RepeatingTimer(30.0, self.mqConn.heartbeat_tick) 
t.start() # every 30 seconds, call heartbeat_tick 

# later 
t.cancel() # cancels execution 
+1

一提的是這個*不*執行每隔30秒,如果'heartbeat_tick()'花費的時間顯著量 – goncalopp

+0

沒錯這可能是重要的,這將每次至少30秒。最多30秒是比較難的。 – Eric

+1

如果你的前臺函數被CPU綁定,GIL會阻止後臺線程執行嗎? –

2

一種方法是使用這樣的circuits應用框架:

from circuits import Component, Event, Timer 


class App(Component): 

    def init(self, mqConn): 
     self.mqConn = mqConn 
     Timer(30, Event.create("heartbeat"), persist=True).register(self) 

    def heartbeat(self): 
     self.mqConn.heartbeat_tick() 


App().run() 

注:我電路:)

筆者這僅僅是一個基本的想法和結構 - 您需要根據您的具體應用和要求進行調整!

1

或者你可以在線程模塊中使用Timer類:

from threading import Timer 

def hello(): 
    print "hello, world" 

t = Timer(30.0, hello) 
t.start() # after 30 seconds, "hello, world" will be printed 
t.cancel() # cancels execution, this only works before the 30 seconds is elapsed 

這不會每x秒啓動一次,而是延遲執行的線程x秒。但是你仍然可以把它放在一個循環中,並使用t.is_alive()來查看它的狀態。

+0

循環在哪裏? – Eric

+0

這將取決於用例? – Joe

+0

這不是也需要在後臺線程? – Eric

2

Eric的回答:你不能繼承Timer的子類,因爲它實際上是一個真正的類的光函數包裝:_Timer。如果你這樣做,你會得到在this post彈出的問題。

使用_Timer,而不是修復它:

from threading import _Timer 

class RepeatingTimer(_Timer): 
    def run(self): 
     while not self.finished.is_set(): 
      self.function(*self.args, **self.kwargs) 
      self.finished.wait(self.interval) 


t = RepeatingTimer(30.0, self.mqConn.heartbeat_tick) 
t.start() # every 30 seconds, call heartbeat_tick 

# later 
t.cancel() # cancels execution 
相關問題