Python倒计时没有睡眠

时间:2012-06-06 00:46:33

标签: python time

我正在使用Twisted套接字,但我听到的是,如果你在使用套接字时使用time.sleep,系统会挂起,套接字会停止运行。有没有办法在没有time.sleep的情况下进行倒计时?

感谢。

1 个答案:

答案 0 :(得分:0)

Twisted有两个选择。您可以使用一个简单的函数来检查条件。

from twisted.internet import reactor
expire = 10
def tick():
    expire -= 1
    if expire == 0:
        reactor.stop()
        return
    reactor.callLater(1, tick)

reactor.callLater(0, tick)
reactor.run()

还有twisted.internet.task.LoopingCall http://twistedmatrix.com/documents/current/api/twisted.internet.task.LoopingCall.html

from twisted.internet.task import LoopingCall

def tick():
    if expired = 0:
        reactor.stop()
        return
    do_something()

task = LoopingCall(tick)
task.start()
reactor.run()

如果您使用的是扭曲的应用程序(扭曲的)或其他多服务,还有twisted.application.internet.TimerService http://twistedmatrix.com/documents/current/api/twisted.application.internet.TimerService.html