19

GTK allows you to set a timeout with g_timeout_add. Just like g_signal_connect, the g_timeout_add function returns an id representing the timeout. So, is there a way to cancel a timeout using the id? Looking through the documentation, I don't see any way to cancel a timeout event, but I would assume there must be some way, otherwise what is the point of the id value returned by g_timeout_add?

So, is there any way to cancel a timeout event, or is this just something that needs to be handled manually by setting a "cancellation flag" which can be checked within the user-provided timeout handler function?

Griwes
  • 8,805
  • 2
  • 43
  • 70
Channel72
  • 24,139
  • 32
  • 108
  • 180

1 Answers1

26

There are two ways to remove a callback registered through g_timeout_add():

  • Have the callback function return FALSE,
  • Call g_source_remove() with the identifier returned by g_timeout_add().
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • is there anyway where I can cancel the call back before the first call. Ex: I schedule it after 10 secs and I decide to cancel it after 5 secs (its not yet called). After the first call back you will get identifier using which you can cancel but is it possible to cancel before that? – Sagar Sakre Aug 27 '14 at 04:09
  • 1
    @Sagar, yes, with `g_source_remove()`. It takes the identifier returned by `g_timeout_add()`, so you don't have to wait for the callback to be invoked. – Frédéric Hamidi Aug 27 '14 at 05:59
  • Oh i got it now. schedule func using g_timeout_add(), using the ret value from g_timeout_add(), you can cancel the call back invocation. Is my understanding is right? – Sagar Sakre Aug 27 '14 at 06:34
  • 1
    For future googling: a message such as `GLib-CRITICAL **: Source ID was not found when attempting to remove it` may indicate that `g_source_remove()` was called to remove a timeout handler that was not propely configured. – anol Mar 20 '15 at 10:05