python定时器5秒执行一次_Python threading.timer-每隔“n”秒重复一次函数

  • Post author:
  • Post category:python


import threading

def setInterval(interval):

def decorator(function):

def wrapper(*args, **kwargs):

stopped = threading.Event()

def loop(): # executed in another thread

while not stopped.wait(interval): # until stopped

function(*args, **kwargs)

t = threading.Thread(target=loop)

t.daemon = True # stop if the program exits

t.start()

return stopped

return wrapper

return decorator

用法:@setInterval(.5)

def function():

“…”

stop = function() # start timer, the first call is in .5 seconds

stop.set() # stop the loop

stop = function() # start new timer

# …

stop.set()cancel_future_calls = call_repeatedly(60, print, “Hello, World”)

# …

cancel_future_calls()