代码之家  ›  专栏  ›  技术社区  ›  freddy888

python每分钟线程化多个函数

  •  1
  • freddy888  · 技术社区  · 6 年前

    我想在无限循环中同时运行几个函数,但所有函数都应该以不同的间隔运行。例如,以下代码:

    while True:
       functionA()
       after 1 minute repeat
       functionB()
       after 2 minutes repeat
    

    我知道如何使用time.sleep或dateime.now()进行工作,但我不知道如何让functa和B在同一个文件中独立运行和等待。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Jared Smith    6 年前
    from threading import Timer
    
    class Interval(object):
        """Interface wrapper for re-occuring functions."""
    
        def __init__(self, f, timeout):
            super(Interval, self).__init__()
            self.timeout = timeout
            self.fn = f
            self.next = None
            self.done = False
            self.setNext()
    
    
        def setNext(self):
            """Queues up the next call to the intervaled function."""
            if not self.done:
                self.next = Timer(self.timeout, self.run)
                self.next.start()
    
            return self
    
    
        def run(self):
            """Starts the interval."""
            self.fn()
            self.setNext()
            return self
    
    
        def stop(self):
            """Stops the interval. Cancels any pending call."""
            self.done = True
            self.next.cancel()
            return self