5

I want to make my function run for a particular period like for 5 seconds; how I can do that ?

Like,

def my_function():
   while(time == 10 seconds):
       ......... #run this for 10 seconds 
def my_next_function(): 
   while(time == 5 seconds):
       ......... #run this for 5 seconds 
Sam
  • 7,252
  • 16
  • 46
  • 65
user3523728
  • 73
  • 2
  • 9
  • Possible duplicate: http://stackoverflow.com/questions/8600161/executing-periodic-actions-in-python – ρss Jun 20 '14 at 09:20

4 Answers4

2

This will definitely help you.

import time

def myfunc():
    now=time.time()
    timer = 0
    while timer != 10:
        end = time.time()
        timer = round(end-now)

def mynextfunc():
    now=time.time()
    timer = 0
    while timer != 5:
        end = time.time()
        timer = round(end-now)


myfunc()
print "myfunc() exited after 10 seconds"

mynextfunc()
print "mynextfunc() exited after 5 seconds"
DOSHI
  • 442
  • 2
  • 23
2

If an individual loop iteration does not take much time:

#!/usr/bin/env python3
from time import monotonic as timer

def my_function():
    deadline = timer() + 10
    while timer() < deadline:
        ......... #run this for 10 seconds 
def my_next_function(): 
    deadline = timer() + 5
    while timer() < deadline:
        ......... #run this for 5 seconds 

Otherwise, see How to limit execution time of a function call in Python.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
1

I'd use a <=, rather than a != there. With the round, you'll get integer times, but if something ugly happens, and you skip a second, it'll run forever!

teo van kot
  • 12,350
  • 10
  • 38
  • 70
0

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)
Stuart
  • 9,597
  • 1
  • 21
  • 30