Search code examples
pythontimergobject

python mainloop, add timed events


I have a Python script that does stuff based on D-Bus events, simplified version of that:

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()

This calls the cb_udisk_dev_add and -rem callback functions. Now I would like to have a timed callback function which I like to call, say every 5 minutes.

It seems that mainloop.run() is a blocked function, so I think I need to add a timer of sorts to the mainloop...?

I have tried implementing a few periodically executing functions from: Executing periodic actions in Python but they are all blocking too, soo the mainloop.run() doesn't get executed.

Any suggestions?


Solution

  • You could use the glib's g_timeout_add_seconds function that registers a callback function to be executed in GMainloop's context. In python, this function is encapsulated in GObject, and you can try the below example code:

    from gi.repository import GObject
    
    def hello():
       print("Hello world!\n")
       return True
    
    GObject.timeout_add_seconds(1, hello)
    loop = GObject.MainLoop()
    loop.run()