What is the best way to repeatedly execute a function every x seconds?

后端 未结 18 2689
不知归路
不知归路 2020-11-21 06:04

I want to repeatedly execute a function in Python every 60 seconds forever (just like an NSTimer in Objective C). This code will run as a daemon and is effectively like call

18条回答
  •  甜味超标
    2020-11-21 06:27

    This seems much simpler than accepted solution - does it have shortcomings I'm not considering? Came here looking for some dead-simple copy pasta.

    import threading, time
    
    def print_every_n_seconds(n=2):
        while True:
            print(time.ctime())
            time.sleep(n)
        
    thread = threading.Thread(target=print_every_n_seconds, daemon=True)
    thread.start()
    
    

    Which asynchronously outputs.

    #Tue Oct 16 17:29:40 2018
    #Tue Oct 16 17:29:42 2018
    #Tue Oct 16 17:29:44 2018
    

    This does have drift. If the task being run takes appreciable amount of time, then the interval becomes 2 seconds + task time, so if you need precise scheduling then this is not for you.**

    Note the daemon=True flag means this thread won't block the app from shutting down. For example, had issue where pytest would hang indefinitely after running tests waiting for this thead to cease.

提交回复
热议问题