python - 如何在 Python 中让函数在 5 秒后返回?

标签 python function time

我想写一个无论如何都会在 5 秒后返回的函数:

def myfunction():
    while passed_time < 5_seconds:
        do1()
        do2()
        do3()
        .
        .
    return

我的意思是,这个函数只运行了 5 秒,5 秒后,它应该结束,然后继续其他函数:

myfunction()
otherfunction()   ----> This should start 5 seconds after myfunction() is executed.

最好的问候

最佳答案

你可以这样做:

def myfunction():
    start = time.time()
    while time.time() < start + 5:
        do1()
        do2()
        do3()

请注意,这将在至少 5 秒后停止 - 如果do1do2do3 每个需要 3 秒,那么这个函数将需要 9 秒。


如果你想在这些调用之间切断myFunction,你可以这样做:

def myfunction():
    todo = itertools.cycle([do1, do2, do3])
    start = time.time()
    while time.time() < start + 5:
        todo.next()()

这种情况需要 6 秒

关于python - 如何在 Python 中让函数在 5 秒后返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12217027/

相关文章:

Python 日志记录不会创建日志文件的多个实例

python - 如何更改seaborn散点图矩阵中的绘图轴,sns.pairplot()

function - ReactJs 全局辅助函数

java - 从两个 Date 对象计算持续时间的错误时间(以分钟为单位)

C++ 如何将日期从输入(字符串年、字符串月、字符串日)转换为时间点

python - 在 Travis CI 上卡住 Python 应用程序

python - 如何转到下一行而不是打印\n?

function - 从 React-Native ListView 行中的子组件调用父函数

ios - 参数是未声明的类型?

android - 小部件中的自定义字体