Python 循环运行特定秒数 [英] Python loop to run for certain amount of seconds
问题描述
我有一个 while 循环,我希望它继续运行 15 分钟.目前是:
I have a while loop, and I want it to keep running through for 15 minutes. it is currently:
while True:
#blah blah blah
(这会运行,然后重新启动.我需要它继续执行此操作,除非在 15 分钟后退出循环)
(this runs through, and then restarts. I need it to continue doing this except after 15 minutes it exits the loop)
谢谢!
推荐答案
试试这个:
import time
t_end = time.time() + 60 * 15
while time.time() < t_end:
# do whatever you do
这将运行 15 分钟 x 60 秒 = 900 秒.
This will run for 15 min x 60 s = 900 seconds.
函数 time.time
返回自 1970 年 1 月 1 日以来的当前时间(以秒为单位).该值是浮点数,因此您甚至可以以亚秒级精度使用它.开始时,t_end 值计算为现在"+ 15 分钟.循环会一直运行,直到当前时间超过这个预设的结束时间.
Function time.time
returns the current time in seconds since 1st Jan 1970. The value is in floating point, so you can even use it with sub-second precision. In the beginning the value t_end is calculated to be "now" + 15 minutes. The loop will run until the current time exceeds this preset ending time.
这篇关于Python 循环运行特定秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!