[Twisted-Python] LoopingCall question

Jean-Paul Calderone exarkun at divmod.com
Thu Jun 26 07:27:10 EDT 2008


On Wed, 25 Jun 2008 23:29:00 -0400, Mike Preshman <mpresh at gmail.com> wrote:
>Hello,
>
>I am trying to run three deferred LoopingCall chains in parallel.
>Here is my code below. I am trying to figure out what is the correct way of
>exiting the polling after I meet some
>condition that the polling satisfies. Right now I am throwing an exception
>which is being caught by an errback. I wait for all three deferred chains to
>complete
>via a DeferredList with (defer.gatherResults) and then I add a callback to
>that in order to stop the reactor.
>
>class PollingException(twisted.python.failure.Failure):
>
>    def __init__(self, var):
>        self.var = var
>

Don't subclass Failure.  Just subclass Exception.

>
>def poll(*args):
>    print "poll", args
>    raise PollingException(args[1])
>
>def errorHandle(failure):
>    print "poll exited"
>    return True
>
>def stopReactor(result):
>    print "about to stop reactor"
>    reactor.stop()
>
>
>t1 = task.LoopingCall(poll, "A")
>d1 = t1.start(1, 3)
>d1.addErrback(errorHandle)
>
>t2 = task.LoopingCall(poll, "B")
>d2 = t2.start(2, 3)
>d2.addErrback(errorHandle)
>
>t3 = task.LoopingCall(poll, "C")
>d3 = t3.start(3, 3)
>d3.addErrback(errorHandle)
>
>dL = defer.gatherResults([d1, d2, d3])
>dL.addCallback(lambda _: reactor.stop())
>
>reactor.run()
>
>However, when I run the code and I try to stop the reactor, I get the
>following exception which I find puzzling.
>
> [snip]
>    raise RuntimeError, "can't stop reactor that isn't running"
>exceptions.RuntimeError: can't stop reactor that isn't running
>

LoopingCall invokes the function it is given immediately, unless you pass
now=False to its initializer.  This means you're stopping the reactor
several times before it's even started.  Try making sure the reactor is
running before poll is ever called.

Jean-Paul




More information about the Twisted-Python mailing list