Python 循环运行特定秒数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24374620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python loop to run for certain amount of seconds
提问by oam811
I have a while loop, and I want it to keep running through for 15 minutes. it is currently:
我有一个 while 循环,我希望它继续运行 15 分钟。目前是:
while True:
#blah blah blah
(this runs through, and then restarts. I need it to continue doing this except after 15 minutes it exits the loop)
(这会运行,然后重新启动。我需要它继续执行此操作,除非在 15 分钟后退出循环)
Thanks!
谢谢!
采纳答案by DrV
Try this:
尝试这个:
import time
t_end = time.time() + 60 * 15
while time.time() < t_end:
# do whatever you do
This will run for 15 min x 60 s = 900 seconds.
这将运行 15 分钟 x 60 秒 = 900 秒。
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.
函数time.time
返回自 1970 年 1 月 1 日以来的当前时间(以秒为单位)。该值是浮点数,因此您甚至可以以亚秒级精度使用它。开始时,t_end 值计算为“现在”+ 15 分钟。循环将一直运行,直到当前时间超过此预设结束时间。
回答by Elliott Frisch
If I understand you, you can do it with a datetime.timedelta
-
如果我理解你,你可以用datetime.timedelta
-
import datetime
endTime = datetime.datetime.now() + datetime.timedelta(minutes=15)
while True:
if datetime.datetime.now() >= endTime:
break
# Blah
# Blah
回答by anonmak9
try this:
尝试这个:
import time
import os
n = 0
for x in range(10): #enter your value here
print(n)
time.sleep(1) #to wait a second
os.system('cls') #to clear previous number
#use ('clear') if you are using linux or mac!
n = n + 1
回答by Hasan Latif
Simply You can do it
只要你能做到
import time
delay=60*15 ###for 15 minutes delay
close_time=time.time()+delay
while True:
##bla bla
###bla bla
if time.time()>close_time
break
回答by Sascha N.
I was looking for an easier-to-read time-loop when I encountered this question here. Something like:
当我在这里遇到这个问题时,我正在寻找一个更容易阅读的时间循环。就像是:
for sec in max_seconds(10):
do_something()
So I created this helper:
所以我创建了这个助手:
# allow easy time-boxing: 'for sec in max_seconds(42): do_something()'
def max_seconds(max_seconds, *, interval=1):
interval = int(interval)
start_time = time.time()
end_time = start_time + max_seconds
yield 0
while time.time() < end_time:
if interval > 0:
next_time = start_time
while next_time < time.time():
next_time += interval
time.sleep(int(round(next_time - time.time())))
yield int(round(time.time() - start_time))
if int(round(time.time() + interval)) > int(round(end_time)):
return
It only works with full seconds which was OK for my use-case.
它仅适用于我的用例的完整秒数。
Examples:
例子:
for sec in max_seconds(10) # -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
for sec in max_seconds(10, interval=3) # -> 0, 3, 6, 9
for sec in max_seconds(7): sleep(1.5) # -> 0, 2, 4, 6
for sec in max_seconds(8): sleep(1.5) # -> 0, 2, 4, 6, 8
Be aware that interval isn't that accurate, as I only wait full seconds (sleep never was any good for me with times < 1 sec). So if your job takes 500 ms and you ask for an interval of 1 sec, you'll get called at: 0, 500ms, 2000ms, 2500ms, 4000ms and so on. One could fix this by measuring time in a loop rather than sleep() ...
请注意,间隔不是那么准确,因为我只等待整整几秒钟(睡眠时间 <1 秒对我来说从来没有任何好处)。因此,如果您的工作需要 500 毫秒,并且您要求间隔 1 秒,您将在以下时间被调用:0、500 毫秒、2000 毫秒、2500 毫秒、4000 毫秒等等。可以通过在循环中测量时间而不是 sleep() 来解决此问题...
回答by Sam Bull
For those using asyncio, an easy way is to use asyncio.wait_for()
:
对于那些使用 asyncio 的人,一个简单的方法是使用asyncio.wait_for()
:
async def my_loop():
res = False
while not res:
res = await do_something()
await asyncio.wait_for(my_loop(), 10)