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

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

    Here's an update to the code from MestreLion that avoids drifiting over time.

    The RepeatedTimer class here calls the given function every "interval" seconds as requested by the OP; the schedule doesn't depend on how long the function takes to execute. I like this solution since it doesn't have external library dependencies; this is just pure python.

    import threading 
    import time
    
    class RepeatedTimer(object):
      def __init__(self, interval, function, *args, **kwargs):
        self._timer = None
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.is_running = False
        self.next_call = time.time()
        self.start()
    
      def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)
    
      def start(self):
        if not self.is_running:
          self.next_call += self.interval
          self._timer = threading.Timer(self.next_call - time.time(), self._run)
          self._timer.start()
          self.is_running = True
    
      def stop(self):
        self._timer.cancel()
        self.is_running = False
    

    Sample usage (copied from MestreLion's answer):

    from time import sleep
    
    def hello(name):
        print "Hello %s!" % name
    
    print "starting..."
    rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
    try:
        sleep(5) # your long-running job goes here...
    finally:
        rt.stop() # better in a try/finally block to make sure the program ends!
    

提交回复
热议问题