Oxfam America banner

Thursday, February 19, 2009

Twisted Sleep

Q: "How do I sleep() in the context of a twisted application without blocking the reactor?"



Here's a simple way:




def sleep(secs):
d = Deferred()
reactor.callLater(secs, d.callback, None)
return d


And here's how you might use the sleep function:




@inlineCallbacks
def doSomeStuff(stuff, throttle):
for thing in stuff:
yield someThing.send(thing)
yield sleep(throttle)


But it's better to just let the reactor schedule things for you:





def doSomeStuff(stuff, throttle):
if not stuff:
return defer.succeed(None)
d = Deferred()
work = list(stuff)
def sendNext()
if not work:
loop.stop()
d.callback(None)
next = work.pop(0)
return someThing.send(next)
loop = LoopingCall(sendNext)
loop.start(throttle)
return d

0 comments:

Post a Comment