如何在 n 时间后停止 while 循环? [英] How would I stop a while loop after n amount of time?

查看:74
本文介绍了如何在 n 时间后停止 while 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 5 分钟后没有达到我想要的效果,我将如何停止它.

how would I stop a while loop after 5 minutes if it does not achieve what I want it to achieve.

while true:
    test = 0
    if test == 5:
        break
    test = test - 1

这段代码让我陷入无限循环.

This code throws me in an endless loop.

推荐答案

尝试以下操作:

import time
timeout = time.time() + 60*5   # 5 minutes from now
while True:
    test = 0
    if test == 5 or time.time() > timeout:
        break
    test = test - 1

您可能还想在此处添加一个短暂的睡眠,以便此循环不会占用 CPU(例如在循环体的开头或结尾处的 time.sleep(1)).

You may also want to add a short sleep here so this loop is not hogging CPU (for example time.sleep(1) at the beginning or end of the loop body).

这篇关于如何在 n 时间后停止 while 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆