在Twisted中每个时刻运行一个函数

1 投票
2 回答
562 浏览
提问于 2025-04-16 01:22

我正在使用twisted框架,我需要记录一个事件开始后经过了多少时间,并在经过一定时间后执行一个动作。

我觉得最好的办法是在每次反应器“滴答”时检查一下时间戳。如果这个方法是最好的,我该怎么做?如果不是,还有什么更好的方法?

2 个回答

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

(我觉得在反应器中并没有真正意义上的“滴答”,至少不是我猜的那种意思。)

1

我想要的功能似乎在这里有描述:在Twisted协议中定期运行一个函数

这是我的代码:

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)

撰写回答