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

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

    I had to do this for a project. What I ended up doing was start a separate thread for the function

    t = threading.Thread(target =heartbeat, args=(worker,))
    t.start()
    

    ****heartbeat is my function, worker is one of my arguments****

    inside of my heartbeat function:

    def heartbeat(worker):
    
        while True:
            time.sleep(5)
            #all of my code
    

    So when I start the thread the function will repeatedly wait 5 seconds, run all of my code, and do that indefinitely. If you want to kill the process just kill the thread.

提交回复
热议问题