开发者

How can I repeat something for x minutes in Python?

开发者 https://www.devze.com 2022-12-27 11:49 出处:网络
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

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开发者_StackOverflow中文版(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.


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


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


You are looking for a scheduler.

Check this thread.


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


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消