如何让一个函数在特定的时间段内运行?

use*_*728 5 python time function python-2.7 python-3.x

我想让我的函数运行一段特定的时间,比如 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 
Run Code Online (Sandbox Code Playgroud)

DOS*_*SHI 2

这绝对会对你有帮助。

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"
Run Code Online (Sandbox Code Playgroud)