简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM