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

前端 未结 13 1287
挽巷
挽巷 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:32

    This is an alternate implementation using function instead of class. Inspired by @Andrew Wilkins above.

    Because wait is more accurate than sleep ( it takes function runtime into account ):

    import threading
    
    PING_ON = threading.Event()
    
    def ping():
      while not PING_ON.wait(1):
        print("my thread %s" % str(threading.current_thread().ident))
    
    t = threading.Thread(target=ping)
    t.start()
    
    sleep(5)
    PING_ON.set()
    
    0 讨论(0)
提交回复
热议问题