Python - 无法在不阻止客户端连接到服务器的情况下在 Tornado 中运行计时器



不是很有经验的龙卷风,所以抱歉,如果这听起来像一个新手的问题。

我正在构建一个卡游戏与客户端使用标准的html/js代码和龙卷风在服务器上。一切都很好,但我需要在服务器上实现一个倒计时,经过一定的时间,一定的代码运行。我正在使用以下python代码,并在发出请求后从tornado调用它

import time
class StartTimer(object):
    timerSeconds = 0
    def __init__(self):
        print "start timer initiated"
    def initiateTime(self, countDownSeconds):
        self.timerSeconds = countDownSeconds
        while self.timerSeconds >= 0:
            time.sleep(1)
            print self.timerSeconds
            self.timerSeconds -=1
            if self.timerSeconds == 0:
                #countdown finishes
                print "timer finished run the code"

    def getTimer(self):
        return self.timerSeconds

倒计时工作得很好,但我有两个问题,首先,而计时器倒计时服务器阻止任何其他连接,并把它们放在队列中,并在计时器完成后运行代码第二,我需要getTimer函数工作,这样一个新的客户端进来知道还有多少时间(基本上得到timerSeconds值)。我可以摆脱定时器不显示给用户,但事实是,代码被封锁绝对是不好的。

请帮

time.sleep()将阻塞,使用add_timeout()代替在这里检查

编辑:抱歉,@Armin Rigo已经回答了

下面是一个例子:

import time
import tornado.ioloop

def delayed_print(s):
    if len(s) == 0:
        ioloop.stop()
    else:
        print s[0]
        ioloop.add_timeout(time.time() + 1, lambda:delayed_print(s[1:]))
ioloop = tornado.ioloop.IOLoop()
delayed_print('hello world')
ioloop.start()

自Tornado 4.0以来,call_later将更加方便。对于相对情况,因为它不需要timedelta对象。

相关内容

最新更新