Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python loop to run for certain amount of seconds

I have a while loop, and I want it to keep running through for 15 minutes. it is currently:

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)

Thanks!

like image 247
oam811 Avatar asked Jun 23 '14 20:06

oam811


People also ask

How do you make a loop run a certain number of time in Python?

The most common way to repeat a specific task or operation N times is by using the for loop in programming. We can iterate the code lines N times using the for loop with the range() function in Python.

How do I run a Python function every 5 minutes?

With the help of the Schedule module, we can make a python script that will be executed in every given particular time interval. with this function schedule. every(5). minutes.do(func) function will call every 5 minutes.

How do you call a function repeatedly after a fixed time interval in Python?

start() and stop() are safe to call multiple times even if the timer has already started/stopped. function to be called can have positional and named arguments. You can change interval anytime, it will be effective after next run.


5 Answers

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.

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.

like image 146
DrV Avatar answered Oct 26 '22 19:10

DrV


If I understand you, you can do it with a datetime.timedelta -

import datetime

endTime = datetime.datetime.now() + datetime.timedelta(minutes=15)
while True:
  if datetime.datetime.now() >= endTime:
    break
  # Blah
  # Blah
like image 44
Elliott Frisch Avatar answered Oct 26 '22 21:10

Elliott Frisch


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
like image 3
Hasan Latif Avatar answered Oct 26 '22 20:10

Hasan Latif


For those using asyncio, an easy way is to use asyncio.wait_for():

async def my_loop():
    res = False
    while not res:
        res = await do_something()

await asyncio.wait_for(my_loop(), 10)
like image 3
Sam Bull Avatar answered Oct 26 '22 20:10

Sam Bull


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() ...

like image 2
Sascha N. Avatar answered Oct 26 '22 21:10

Sascha N.