简体   繁体   English

Python - 如何在必要时杀死计时器而不是让它永远运行?

[英]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 如果您知道my_timer()函数内部不应再次调用它,则返回False
  • Alternatively, store the event id that timeout_add() returns and do a g_source_remove(event_id) when it's no longer needed 或者,存储timeout_add()返回的事件id,并在不再需要时执行g_source_remove(event_id)

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. 建议:如果您不需要亚秒精度,请使用timeout_add_seconds()。 It allows glib to optimize things and is better for power management. 它允许glib优化事物,更好地进行电源管理。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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