扭曲:延迟重复触发?

发布于 2024-09-15 02:43:36 字数 140 浏览 4 评论 0原文

Deferred 是在 Twisted 中进行异步处理的好方法。然而,顾名思义,它们用于延迟计算,仅运行和终止一次,触发回调一次。如果我进行重复计算(例如单击按钮)怎么办?是否有类似延迟的对象可以重复触发,并在触发时调用附加到它的所有回调?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悲喜皆因你 2024-09-22 02:43:36

我现在已经设置好了。对于我有限的用例,它可以满足我的需求。

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)

有人告诉我这是否可怕。

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.

梦里°也失望 2024-09-22 02:43:36

您可能正在寻找的是 defer。 inlineCallbacks 它允许您使用生成器来创建 Deferred 的顺序链。本质上,您可以创建一个永不结束(或有条件结束)的生成器,并继续从中生成 Deferreds。

krondo.com 上有一篇关于使用 inlineCallbacks 的精彩文章。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文