1

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.

1
  • 1
    You may want to look at a threading solution that releases the GIL. Commented Dec 26, 2018 at 21:45

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain what the problem was, and what the solution does differently?
@PeterWood added a bit of explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.