Reputation: 606
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
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
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
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