ErikT
ErikT

Reputation: 606

How can I repeat something for x minutes in Python?

I have a program (temptrack) where I need to download weather data every x minutes for x amount of hours. I have figured out how to download every x minutes using time.sleep(x*60), but I have no clue how to repeat this process for a certain amount of hours.

UPDATE: Thank you to everyone who posted a solution. I marked the example using "datetime.datetime.now() + datetime.timedelta(hours=x)" as the best answer because I could understand it the best and it seems like it will work very well for my purpose.

Upvotes: 4

Views: 4508

Answers (5)

user221209
user221209

Reputation:

I've just found sched in the Python standard library.

Upvotes: 4

user97370
user97370

Reputation:

Compute the time you want to stop doing whatever it is you're doing, and check each time that the time limit hasn't expired. Like this:

finish_time = datetime.datetime.now() + datetime.timedelta(hours=6)
while datetime.datetime.now() < finish_time:
    do_something()
    sleep_for_a_bit()

Upvotes: 5

user297250
user297250

Reputation:

May be a bit of overkill, but for running background tasks, especially if you need a GUI, I'd recommend checking out the PyQt route with QSystemTrayIcon and QTimer

Upvotes: 0

Macarse
Macarse

Reputation: 93183

You are looking for a scheduler.

Check this thread.

Upvotes: 3

Michael Mrozek
Michael Mrozek

Reputation: 175775

Maybe I'm misunderstanding you, but just put it in a loop that runs a sufficient number of times. For example, to download every 5 minutes for 2 hours you need to download 24 times, so:

for i in range(24):
    download()
    sleep(5*60)

If you need it to be parameterizable, it's just:

from __future__ import division
from math import ceil
betweenDLs = 5 # minutes
totalTime = 2*60 # minutes
for i in range(int(ceil(totalTime/betweenDLs))):
    download()
    sleep(betweenDLs*60)

Upvotes: -1

Related Questions