【问题标题】:Run a function each tick in Twisted在 Twisted 中的每个刻度运行一个函数
【发布时间】:2010-07-15 23:52:27
【问题描述】:

我正在使用扭曲的框架,我需要跟踪自事件开始以来经过了多少时间,并在经过一定时间后执行操作。

在我看来,最好的方法是检查反应堆的每个滴答声的时间戳。如果这是最好的方法,我该怎么做?如果不是,有什么更好的方法?

【问题讨论】:

    标签: python twisted timing


    【解决方案1】:

    你想使用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()
    

    (我不认为反应堆中真的有任何“滴答声”之类的东西,至少,不是我猜你的意思。)

    【讨论】:

    • 这并不完全符合我的要求。我最终使用 task.LoopingCall 每秒运行两个时间戳之间的比较。请参阅我的答案中的链接。
    • @Alex。你搞定了。 LoopingCall - 如果你想,呃,循环通话和CallLater 如 Glyph 提到的,如果你想安排通话。它是sleepdoWork 的绝佳替代品 - 因为sleep 会阻止reactor 而您不希望这样。
    【解决方案2】:

    我正在寻找的功能似乎在这里描述: 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      相关资源
      最近更新 更多