Python Countdown w/o Sleep
Question: I am working on a Twisted socket, but what I've heard is that if you use
time.sleep while using a socket, the system hangs and the socket goes on halt.
Is there any way of doing a countdown without time.sleep?

Thanks.


Answer: Twisted has a couple of options. You could use a simple function to check a
condition.

    
    
    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()
    

There is also 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()
    

If you are using a twisted application (twistd) or some other multiservice,
there is also twisted.application.internet.TimerService
<http://twistedmatrix.com/documents/current/api/twisted.application.internet.TimerService.html>

