Ash*_*abi 4 python timer tornado countdown
在 Tornado 中不是很有经验,如果这听起来像一个新手问题,那么抱歉。
我正在使用标准的 html/js 代码和服务器上的龙卷风与客户端构建纸牌游戏。一切正常,但是我需要在服务器上实现倒计时,在一定时间后运行某个代码。我正在使用以下 python 代码并在发出请求后从龙卷风中调用它
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
Run Code Online (Sandbox Code Playgroud)
倒计时工作正常,但是我首先有两个问题,而计时器正在倒计时服务器会阻止任何其他连接并将它们放入队列并在计时器第二次完成后运行代码,我需要 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()
Run Code Online (Sandbox Code Playgroud)