python - 带回调的扭曲模拟计时器

标签 python callback twisted

我是扭曲的新手,我想模拟计时器或类似的东西。

我拥有的是:

def whatToCall():
    print 'Before: ' + str(len(globals.session_manager))
    for ses in globals.session_manager:
        if ses.expired is True:
            globals.session_manager[ses.id] = None
    print 'After: ' + str(len(globals.session_manager))
    reactor.callLater(15, whatToCall(), None)

def callBacks():
    reactor.callLater(15, whatToCall(), None)
....
#: Start the reactor
    reactor.callWhenRunning(callBacks())
    reactor.listenTCP(globals.port, factory)
    reactor.run()

首先,我第一次打电话不需要 15 秒。其次,这显然是行不通的。我理解回调链和延迟的概念,但对此遇到了一些困难。

基本上,我想检查是否有任何 session 不时过期,并且每次都想安排它。

已解决:使用扭曲的任务:

def checkForExpiredSessions():
   print 'Before: ' + str(len(globals.session_manager))
   for i, ses in enumerate(globals.session_manager):
      if ses.expired is True:
         del globals.session_manager[i]
   print 'After: ' + str(len(globals.session_manager))


def callBacksRun():
  l = task.LoopingCall(checkForExpiredSessions)
  l.start(15.0)

最佳答案

表达式:

reactor.callWhenRunning(callBacks())

首先调用 callBacks,然后将返回值传递给reactor.callWhenRunning。类似的情况也适用于:

reactor.callLater(15, whatToCall(), None)

reactor.callWhenRunningreactor.callLater 都接受可调用对象作为参数。除非您期望callBacks返回一个将由 react 器调用的可调用对象,否则您想要编写以达到所需效果的内容是:

reactor.callWhenRunning(callBacks)

reactor.callLater(15, whatToCall)

关于python - 带回调的扭曲模拟计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28217487/

相关文章:

python - 如何在for循环中读取这些元组并转换int类型?

python - 格式化表单数据?

python - Pandas 插值 'time' 与 'linear'

jquery - 将 $(this) 传递给 jQuery 中的回调?

python - twistd 在 *.tac 文件中使用 usage.options

python - 将表从 InnoDB 转换为 MyISAM 时出现 "A foreign key constraint fails"

javascript - JavaScript Promise 中 return 的用法

javascript - jQuery 中 AJAX 回调返回值处理

python - 导入错误 : cannot import name SerialPort on Twisted

python - 为什么 Twisted Manhole ConnectionDone 是一个错误?