1

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?

Alex Bliskovsky
  • 5,973
  • 7
  • 32
  • 41

2 Answers2

2

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
  • 31,152
  • 11
  • 87
  • 129
  • 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 Jul 16 '10 at 12:53
  • @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. – Jeffrey Jose Jul 17 '10 at 10:54
1

The functionality I was looking for seems to be described here: 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)
Community
  • 1
  • 1
Alex Bliskovsky
  • 5,973
  • 7
  • 32
  • 41