views:

47

answers:

2

I'm using the twisted framework, and I need to keep track of how much time has passed since an event has started, and perform an action when a certain amount has passed.

The best way to do that seems to me to be to check against a time-stamp each tick of the reactor. If it is the best way, how do I do it? If it isn't, what's a better way?

+1  A: 

The functionality I was looking for seems to be described here: http://stackoverflow.com/questions/315716/running-a-function-periodically-in-twisted-protocol

Here's my code:

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)
Alex Bliskovsky
+1  A: 

You want to use callLater.

Here's a complete, runnable example which does what you are asking, "perform an action when a certain amount (of time) has passed since an event has started".

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()

(I don't think there's really any such thing as a 'tick' in the reactor, at least, not in the sense that I'm guessing you mean.)

Glyph
This doesn't quite do what I wanted. I ended up using task.LoopingCall to run a comparison between two timestamps each second. See the link in my answer.
Alex Bliskovsky
@Alex. You nailed it. `LoopingCall` - if you want, er, Looping Calls and `CallLater` as Glyph mentioned if you wanna schedule a call. Its a superior alternative to `sleep` and then `doWork` - since `sleep` would block the `reactor` and you dont want that.
jeffjose