开发者

Twisted: deferred that fires repeatedly?

Deferreds are a great way to do asynchronous processing in Twisted. However, they, like the name implies, are for deferred computations, which only run and terminate once, firing the callbacks once开发者_如何转开发. What if I have a repeated computation, like a button being clicked? Is there any Deferred-like object that can fire repeatedly, calling all callbacks attached to it whenever it is fired?


I've set this up for now. For my limited use case it does what I want.

class RepeatedDeferred:
    def __init__(self):
        self.callbacks = []

        self.df = defer.Deferred()

    def addCallback(self, callback):
        self.callbacks.append(callback)

        self.df.addCallback(callback)

    def callback(self, res):
        self.df.callback(res)

        self.df = defer.Deferred()
        for c in self.callbacks:
            self.df.addCallback(c)

Someone let me know if this is terrible.


What you might be looking for is defer.inlineCallbacks which allows you to use a generator to create a sequential chain of Deferreds. Essentially you could just create a generator that never ends (or ends conditionally) and keep generating Deferreds from that.

There is a great writeup on using inlineCallbacks at krondo.com.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜