views:

216

answers:

5

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.

A: 

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)
Michael Mrozek
This is a simple solution, but it might not be quite what is wanted if the time to execute the function is similar in magnitude to the time between executions.
Mark Byers
Thank you. Your first example works well. I'll just use "for i in range(totalTime/frequency)" and that should work well. I know it will round (as I'm using integers, not floating point) but it does not have to be very accurate.
ErikT
Try to avoid using range() unless you are needing for a real list. If you just need to run a for use xrange instead. This will optimize your code, because range() allocs a whole list, while xrange() is just an iterator. NOTE: in python3 there's only range() and behaves like xrange()
Dacav
I would use select() for doing this :p
dzen
UPDATE: nevermind, using "for i in range(totalTime/frequency)" does not appear to work that well (meaning it is too inaccurate to use). Thanks, I'll check out xrange() and select().
ErikT
+3  A: 

You are looking for a scheduler.

Check this thread.

Macarse
No, not really. But thank you anyway.
ErikT
A: 

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

Brendan Abel
+3  A: 

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

dzen
+4  A: 

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()
Paul Hankin
This is exactly what I was looking for, even though I didn't know it. Thank you very much.
ErikT