Search code examples
pythonmultithreadingtimerpygobject

How to unset a timer set by python gobject.timeout_add ? threads?


I want to set timer in a thread and kill that thread when I want to unset the timer set by gobject.timeout_add, is this a good way to do this?

basically I want to run a function for every 180 seconds but I want to be able to stop it whenever I want to(called from another function). How to achieve this properly?

I have read that killing a thread is bad! How bad is it for simple tasks like this?


Solution

  • According to the docs when you call gobject.timeout_add it returns a int which is unique for that timeout source. And then also farther down in the docs, you see a function called gobject.source_remove which takes, as an argument, an int that will remove the event source for you without having to mess with threads and the like. Example:

    integer_id = gobject.timeout_add( 180000, callback_func)
    #And then somewhere else in your code...
    gobject.source_remove(integer_id) #This will stop the timeout_add from occurring!
    

    Hope that helps!