user285594
user285594

Reputation:

Python - how to kill the timer when necessary instead of let it run forever?

How do i kill this timer, once it was executed/started ?

def my_timer(*args):
    return True# do ur work here, but not for long

gtk.timeout_add(1000, my_timer) # call every min

Upvotes: 0

Views: 270

Answers (2)

user285594
user285594

Reputation:

def my_timer(*args):
    return True# do ur work here, but not for long

t =gtk.timeout_add(1000, my_timer) # call every min
time.sleep(5)
gtk.timeout_remove(t)              # kill the timer

Upvotes: 0

Jussi Kukkonen
Jussi Kukkonen

Reputation: 14607

Two options:

  • If you know inside my_timer() function that it should not be called again, just return False
  • Alternatively, store the event id that timeout_add() returns and do a g_source_remove(event_id) when it's no longer needed

Also, the "call every minute" comment is wrong: the handle will be called every second.

Suggestion: use timeout_add_seconds() if you do not need sub-second accuracy. It allows glib to optimize things and is better for power management.

Upvotes: 1

Related Questions