簡體   English   中英

Python - 無法阻止客戶端連接到服務器,無法在Tornado中運行計時器

[英]Python - Can't run a timer in Tornado without blocking the clients from connecting to the server

龍卷風不是很有經驗,如果這聽起來像是一個新手問題,那就很抱歉。

我正在與客戶一起使用標准的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

倒計時工作正常然而我首先有兩個問題,而計時器正在倒計時服務器阻止任何其他連接並將它們放入隊列並在計時器完成后運行代碼第二,我需要getTimer函數才能工作這樣一個新的客戶進來知道剩下多少時間(基本上得到timerSeconds值)。 我可能會忘記向用戶顯示的計時器但是代碼被阻止的事實絕對不是好事。

請幫忙

add_timeout() 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以來, IOLoop.call_later將更加方便。 對於相對情況,因為它不需要timedelta對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM