python mainloop,添加定时事件

python mainloop, add timed events

我有一个 Python 脚本可以根据 D-Bus 事件执行操作,简化版本:

import dbus
from dbus.mainloop.glib import DBusGMainLoop
import gobject

DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()

# Initialize a main loop
mainloop = gobject.MainLoop()
bus.add_signal_receiver(cb_udisk_dev_add, signal_name='DeviceAdded', dbus_interface="org.freedesktop.UDisks")
bus.add_signal_receiver(cb_udisk_dev_rem, signal_name='DeviceRemoved', dbus_interface="org.freedesktop.UDisks")

mainloop.run()

这会调用 cb_udisk_dev_add 和 -rem 回调函数。现在我想要一个我喜欢调用的定时回调函数,比如每 5 分钟一次。

mainloop.run() 似乎是一个阻塞函数,所以我想我需要在主循环中添加一个定时器之类的...?

我已经尝试实现一些定期执行的函数: Executing periodic actions in Python 但是它们也都阻塞了,所以 mainloop.run() 没有被执行。

有什么建议吗?

您可以使用 glib 的 g_timeout_add_seconds 函数来注册一个回调函数,以便在 GMainloop 的上下文中执行。在python中,该函数被封装在GObject中,您可以试试下面的示例代码:

from gi.repository import GObject

def hello():
   print("Hello world!\n")
   return True

GObject.timeout_add_seconds(1, hello)
loop = GObject.MainLoop()
loop.run()