如何使函数在特定时间段内运行?

时间:2014-06-20 09:09:25

标签: python function python-2.7 python-3.x time

我想让我的功能运行一段特定的时间,比如5秒;我怎么能这样做?

像,

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 

4 个答案:

答案 0 :(得分:1)

这肯定对你有帮助。

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"

答案 1 :(得分:0)

我使用的是<=,而不是!=。通过回合,您将获得整数倍,但如果发生了丑陋的事情,并且您跳过了一秒钟,那么它将永远运行!

答案 2 :(得分:0)

如果单个循环迭代不需要花费太多时间:

#!/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 

否则,请参阅How to limit execution time of a function call in Python

答案 3 :(得分:0)

我假设您想要重复整个功能,直到时间到了,而不是试图在时间中途中断功能(这将更加困难)。一个很好的解决方案是使用装饰器:

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

此代码假定您不想对my_func的返回值执行任何操作,但可以轻松调整以收集返回值,以防万一。

如果您不需要将任何参数传递给my_func,则更简单:

def repeat_for(seconds, func):
    stop = seconds + time.time()
    while time.time() <= stop:
        func()

def my_func():
    # ...

repeat_for(10, my_func)