[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:
>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
>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)
>t2 = task.LoopingCall(poll, "B")
>d2 = t2.start(2, 3)
>t3 = task.LoopingCall(poll, "C")
>d3 = t3.start(3, 3)
>dL = defer.gatherResults([d1, d2, d3])
>dL.addCallback(lambda _: reactor.stop())
>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.


More information about the Twisted-Python mailing list