from __future__ import print_function 
import sys 
import threading 
from gi.repository import Gtk, Gdk, GObject


class LoopingCall: 

    def __init__(self, timeout, function, args=[], kwds={}): 
        self.__function = function 
        self.__args = args 
        self.__kwds = kwds 
        self.__timer = None 
        self.start(timeout) 

    def start(self, period=None): 
        self.stop() 
        if period is not None: 
            self.__period = period 
        self.__timer = threading.Timer(self.__period, self.__call) 
        self.__timer.start() 

    def stop(self): 
        if self.__timer: 
            self.__timer.cancel() 
            self.__timer = None 

    def __call(self): 
        self.__function(*self.__args, **self.__kwds) 
        self.start() 

# GObject.threads_init()
Gtk.init(sys.argv) 
win = Gtk.Window() 
btn = Gtk.Button(stock=Gtk.STOCK_QUIT) 
win.add(btn) 
win.connect('destroy', Gtk.main_quit) 
btn.connect('clicked', Gtk.main_quit) 
win.show_all() 
lc = LoopingCall(2, print, ['ping']) 
Gtk.main() 
lc.stop() 

