0

I have two functions, function1 and function2. I want to execute function1 for only 5 seconds, and then execute function2 for only 3 seconds and then repeat it.

I tried time.sleep() function, but it freezes entire program not executing any function.

I tried asyncio and threading, but it just executing both functions at same time.

def function1():
    //do something

def funtion2():
    //do something else

while True:
    function1()
    // execute function1 for 5 seconds

    function2()
    // execute function2 for 3 seconds
ddejohn
  • 8,775
  • 3
  • 17
  • 30
  • 2
    what do you mean by "execute function for x seconds"? Do you want the function executed ONCE then pause for up to x seconds, or do you want the function to repeatedly execute until x seconds pass? – BatWannaBe Oct 30 '21 at 18:25
  • I want to repeatedly execute function for x seconds – user17288277 Oct 31 '21 at 03:28

1 Answers1

1

How precise do you need to be? Are you needing to account for the runtime of the functions themselves? That will be quite difficult.

Here's a simple approach:

import time  # built-in module


def timed_execution(func, s, *args, **kwargs):
    t0 = time.time()
    while True:
        func(*args, **kwargs)
        if time.time() - t0 >= s:
            break


timed_execution(function1, 5)
timed_execution(function2, 3)

If you'd like to get a little more fancy, and the times your functions need to execute is always the same, you could use a decorator:

import time


def timer(s):
    def timed_func(func):
        def timed_execution(*args, **kwargs):
            t0 = time.time()
            while True:
                func(*args, **kwargs)
                if time.time() - t0 >= s:
                    break
        return timed_execution
    return timed_func


@timer(5)
def function1():
    pass


@timer(3)
def function2():
    pass

If you want to use a decorator with a parameter for the amount of time, but only optionally, you'll need to do a bit more work. See how to do a conditional decorator.

ddejohn
  • 8,775
  • 3
  • 17
  • 30