I have several functions I would like to run in an infinite loop simultaneously, but all functions should be run at different intervals. For example, the following code:
while True:
functionA()
after 1 minute repeat
functionB()
after 2 minutes repeat
I know hot to work with time.sleep or dateime.now(), but I do not know how to get functionA and B to run and wait independently of each other in the same file.
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
Pass the functions and timeouts as arguments. The Timer class from the threading module does most of what you need (running a function after a certain time has passed) the wrapper class I added just adds the repetition, makes it easy to start it, stop it, pass it around, etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.