Python 在Twisted中的每个勾号上运行一个函数
我使用的是twisted框架,我需要跟踪事件开始后经过的时间,并在经过一定时间后执行操作Python 在Twisted中的每个勾号上运行一个函数,python,twisted,timing,Python,Twisted,Timing,我使用的是twisted框架,我需要跟踪事件开始后经过的时间,并在经过一定时间后执行操作 在我看来,最好的方法是检查反应堆的每一个滴答声的时间戳。如果这是最好的方法,我该怎么做?如果不是,还有什么更好的方法呢?我正在寻找的功能如下所述: 这是我的密码: def check_time(self): for game in self.games: if self.games[game]['state'] == 'GAME':
在我看来,最好的方法是检查反应堆的每一个滴答声的时间戳。如果这是最好的方法,我该怎么做?如果不是,还有什么更好的方法呢?我正在寻找的功能如下所述: 这是我的密码:
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)
你想用
下面是一个完整的、可运行的示例,它满足了您的要求,“在事件开始后经过一定时间后执行操作”
(我不认为反应堆里真的存在“滴答声”,至少我猜你的意思是这样的。)这并不是我想要的。最后,我使用task.LoopingCall在每秒两个时间戳之间运行比较。请参阅我答案中的链接。@Alex。你搞定了
LoopingCall
-如果您想要,呃,循环调用和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()