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

后端 未结 18 2694
不知归路
不知归路 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:25

    You might want to consider Twisted which is a Python networking library that implements the Reactor Pattern.

    from twisted.internet import task, reactor
    
    timeout = 60.0 # Sixty seconds
    
    def doWork():
        #do work here
        pass
    
    l = task.LoopingCall(doWork)
    l.start(timeout) # call every sixty seconds
    
    reactor.run()
    

    While "while True: sleep(60)" will probably work Twisted probably already implements many of the features that you will eventually need (daemonization, logging or exception handling as pointed out by bobince) and will probably be a more robust solution

提交回复
热议问题