Skip to content

Instantly share code, notes, and snippets.

@stoensin
Created January 11, 2020 10:23
Show Gist options
  • Save stoensin/e43396a59f4d7f5e573ce4c3995aa7e6 to your computer and use it in GitHub Desktop.
Save stoensin/e43396a59f4d7f5e573ce4c3995aa7e6 to your computer and use it in GitHub Desktop.
from threading import Timer
def hello():
print("hello")
class RepeatingTimer(Timer):
'''
RepeatingTimer 的 run 方法会一直执行 while 循环体,在循环体了会执行用户传入的 function 对象,并等待指定的时间。当用户想退出定时器时,只需要调用 cancel 方法,将 flag 置为 True 便不会继续执行循环体了。这样便完成了一个还不错的循环定时器。
'''
def run(self):
while not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.wait(self.interval)
def cancel(self):
"""Stop the timer if it hasn't finished yet"""
self.finished.set()
t = RepeatingTimer(10.0, hello)
t.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment