使用 GLib.source_remove() 避免来自 GLib 的警告

Avoiding warning from GLib with GLib.source_remove()

当我的程序需要使用

设置 GLib 超时函数的一部分时
self.timeout_id = GLib.timeout_add_seconds(refresh, self._check_price)

我用

def stop(self):
    if self.timeout_id:
        GLib.source_remove(self.timeout_id)

确保此 timeout_id 在尝试删除它之前仍然存在。

但我仍然时不时收到这些讨厌的错误消息:

Warning: Source ID 443 was not found when attempting to remove it
GLib.source_remove(self.timeout_id)

怎么办?

源显然是通过 stop() 以外的其他控制路径删除的。我在这里(根据您提供的代码)能想到的唯一候选方法是 self._check_price 方法。如果你从那里返回 False/GLib.SOURCE_REMOVE,你也应该取消设置 self.timeout_id:

def _check_price(self):
    …
    self.timeout_id = 0
    return GLib.SOURCE_REMOVE