I'm assuming you want to repeat the whole function until time is up, rather than trying to interrupt the function midway through it time is up (which would be more difficult). One nice solution is to use a decorator:
import time
def repeat(func):
def inner(*args, **kwargs):
if 'repeat_time' in kwargs:
stop = kwargs.pop('repeat_time') + time.time()
while time.time() <= stop:
func(*args, **kwargs)
else:
func(*args, **kwargs)
return inner
@repeat
def my_func():
# ...
my_func() # calls my_func once
my_func(repeat_time=10) # repeatedly calls my_func for 10 seconds
This code assumes you don't want to do anything with the return values from my_func
, but can easily be adapted to collect the return values in case you do.
Or simpler if you do not need to pass any parameters to my_func
:
def repeat_for(seconds, func):
stop = seconds + time.time()
while time.time() <= stop:
func()
def my_func():
# ...
repeat_for(10, my_func)