2010-07-15 18 views
1

我正在使用扭曲的框架,並且需要跟蹤自事件啓動以來已經過了多長時間,並在一定數量過去時執行操作。運行Twisted中的每個勾號函數

做到這一點的最佳方法似乎是檢查反應堆每個滴答時間的時間戳。如果這是最好的方法,我該怎麼做?如果不是,那麼更好的方法是什麼?

回答

1

我一直在尋找的功能似乎是這裏描述: Running a function periodically in twisted protocol

這裏是我的代碼:

def check_time(self): 
     for game in self.games: 
      if self.games[game]['state'] == 'GAME': 
       game_start_time = self.games[game]['starttime'] 
       if game_start_time is None: 
        continue 
       elif game_start_time + 300 > time.time(): 
        #300 seconds = 5 minutes. 
        continue 
       else: 
        self.end_game(game) 
def __init__(self): 
    self.timecheck = task.LoopingCall(self.check_time) 
    self.timecheck.start(1) 
2

你想用callLater

下面是一個完整的可運行示例,它可以滿足您的要求,「在事件啓動後經過一段時間後執行操作」。

from twisted.internet import reactor 
certainAmount = 0.73 # this is in seconds 
def startedEvent(): 
    print 'started event' 
    reactor.callLater(certainAmount, performAnAction) 

def performAnAction(): 
    print 'performed an action' 
    reactor.stop() 
startedEvent() 
reactor.run() 

(我不認爲有真正作爲反應器內的「滴答」任何這樣的事情,至少,不是在這個意義上,我猜你的意思。)

+0

這不相當做我想要的。我最終使用task.LoopingCall在每秒兩個時間戳之間運行比較。請參閱我答案中的鏈接。 – 2010-07-16 12:53:48

+0

@Alex。你釘了它。 'LoopingCall' - 如果你想要的話,呃,如果你想安排一個電話,就會提到Looping Calls和'CallLater'作爲字形。它是'睡眠'和'doWork'的最佳替代方案 - 因爲'sleep'會阻止'reactor',你不需要這個。 – 2010-07-17 10:54:50

相關問題