[Twisted-Python] Cancel/stop Deferred() at any time

David Bolen db3l.net at gmail.com
Tue Jul 14 15:22:29 MDT 2009


vitaly at synapticvision.com writes:

> "cancel" callback - stop running now what you've been asked to exec.
> Example: some SQL query that takes 5 min and I need to cancel it  
> anywhere in the middle and it, of course, it doesn't matter what the  
> result set.

Note that the Deferred itself has no notion of the underlying
operation - it's just a placeholder for the callback chain to run.  So
trying to get from the deferred back to, for example, the database
query that will eventually use it for the result, is sort of like the
classic Python question of asking what name refers to an object, when
the object really has no idea who holds a reference to it.

If you actually want to try to interrupt a specific operation, then
you'll have to go to the actual application code performing the
operation, and that code will have to have a way to actually cancel an
ongoing activity.  It can then trigger the deferred chain with an
appropriate result (or probably Failure) that indicates cancellation.
That's going to be application-code specific, as Jean-Paul suggested.
In the database case, some database wrappers may support requesting an
interruption of an active query, but some might not.

If, however, you just want to avoid any existing deferred callback
chain from being triggered, but can let the operation proceed while
ignoring its result, I'd think you could just pause the deferred and
never resume it.  That will keep the deferred from triggering any
further callbacks past the point when it was paused, but won't
actually interrupt any currently active operations that the deferred
represents.  If you have code blocked waiting on that deferred (your
second example) it'll never complete without additional cheating -
perhaps initiating a fake callback on the chain first, though you'd
have to use some internals of Deferred or else risk a pause during the
callback opening up a window where the original source could attempt
to re-trigger the callback.

-- David





More information about the Twisted-Python mailing list