【问题标题】:Run only last python function call within some timeframe?在某个时间范围内只运行最后一个 python 函数调用?
【发布时间】:2020-05-01 16:17:33
【问题描述】:

假设我有一个更新应用程序内部状态的函数:

def on_change(*args, **kwargs):
    pass  # some compute intensive state change

这个函数每秒最多可以运行一百次(由于许多鼠标滚轮事件触发了更新)——我只想执行一次上述函数,并且只执行最后一次调用。

管理这种情况的最佳设计模式是什么?我能想到的唯一方法是为每个 on_change 调用生成一个单独的线程并在它们之间共享一个变量,但这听起来过于混乱......

谢谢!

【问题讨论】:

标签: python multithreading python-asyncio coroutine


【解决方案1】:
class Waiter:
    def __init__(self):
        self.args = ()
        self.kwargs = {}
        self.changed = False

    def on_change(self, *args, **kwargs):
        # This is the event handler
        # It does nothing but save the latest arguments
        self.args = args
        self.kwargs = kwargs
        self.changed = True

    def tick(self):
        # Call this function once per second, or whatever
        if self.changed:
            # Do your updates, using self.args and self.kwargs
            self.changed = False

由于您提到鼠标事件,显然您正在编写一个 GUI 应用程序。根据我的经验,所有的 GUI 引擎都有计时器和定期调用函数的能力。使用该功能定期调用 tick。

【讨论】:

    猜你喜欢
    • 2011-11-12
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多