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

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

    from threading import Timer
    def TaskManager():
        #do stuff
        t = Timer( 1, TaskManager )
        t.start()
    
    TaskManager()
    

    Here is small sample, it will help beter understanding how it runs. function taskManager() at the end create delayed function call to it self.

    Try to change "dalay" variable and you will able to see difference

    from threading import Timer, _sleep
    
    # ------------------------------------------
    DATA = []
    dalay = 0.25 # sec
    counter = 0
    allow_run = True
    FIFO = True
    
    def taskManager():
    
        global counter, DATA, delay, allow_run
        counter += 1
    
        if len(DATA) > 0:
            if FIFO:
                print("["+str(counter)+"] new data: ["+str(DATA.pop(0))+"]")
            else:
                print("["+str(counter)+"] new data: ["+str(DATA.pop())+"]")
    
        else:
            print("["+str(counter)+"] no data")
    
        if allow_run:
            #delayed method/function call to it self
            t = Timer( dalay, taskManager )
            t.start()
    
        else:
            print(" END task-manager: disabled")
    
    # ------------------------------------------
    def main():
    
        DATA.append("data from main(): 0")
        _sleep(2)
        DATA.append("data from main(): 1")
        _sleep(2)
    
    
    # ------------------------------------------
    print(" START task-manager:")
    taskManager()
    
    _sleep(2)
    DATA.append("first data")
    
    _sleep(2)
    DATA.append("second data")
    
    print(" START main():")
    main()
    print(" END main():")
    
    _sleep(2)
    DATA.append("last data")
    
    allow_run = False
    

提交回复
热议问题