Python threading.timer - repeat function every 'n' seconds

前端 未结 13 1406
挽巷
挽巷 2020-11-22 09:45

I want to fire off a function every 0.5 seconds and be able to start and stop and reset the timer. I\'m not too knowledgeable of how Python threads work and am having diffic

13条回答
  •  情话喂你
    2020-11-22 10:08

    From Equivalent of setInterval in 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
    

    Usage:

    @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() 
    

    Or here's the same functionality but as a standalone function instead of a decorator:

    cancel_future_calls = call_repeatedly(60, print, "Hello, World")
    # ...
    cancel_future_calls() 
    

    Here's how to do it without using threads.

提交回复
热议问题