I'm writing a weather display program for my Raspberry Pi in python that fetches data using weather.com's api. As it stands, I have set it to sleep for 5 minutes after each main 'while' loop. This is because I don't want the Pi constantly using the wifi to fetch the same weather data. The problem with this is if I try to close or alter the program in any way, it waits to finish the time.sleep() function before continuing. I would like to add buttons to create a scroll menu but currently, the program will hang in that time.sleep() function before continuing. Is there an alternative I can use to delay the fetching of data while keeping program responsiveness?
Asked
Active
Viewed 2,413 times
1
-
It's not really clear what you're asking, you probably want to write up a [MCVE] that demonstrates the problems you're running into. – pvg Dec 16 '16 at 05:56
-
You can decrease sleeping time to 1 sec and put it in a loop: 'for i in xrange(300): time.sleep(1)`. – Gennady Kandaurov Dec 16 '16 at 05:57
-
`pygame` has `pygame.time` which you can use to check time and execute command in `while True` loop. – furas Dec 16 '16 at 11:30
3 Answers
2
You can do something like this:
import time, threading
def fetch_data():
# Add code here to fetch data from API.
threading.Timer(10, fetch_data).start()
fetch_data()
fetch_data method will be executed inside a thread so you wont have much problem. There is also a delay before calling the method. So you wont be bombarding the API.
Example source: Executing periodic actions in Python

Community
- 1
- 1

Vikash Singh
- 13,213
- 8
- 40
- 70
1
Create a timer with python's time
module
import time
timer = time.clock()
interval = 300 # Time in seconds, so 5 mins is 300s
# Loop
while True:
if timer > interval:
interval += 300 # Adds 5 mins
execute_API_fetch()
timer = time.clock()

underscoreC
- 729
- 6
- 13
0
Pygame has pygame.time.get_ticks()
which you can use to check time and use it to execute function in mainloop.
import pygame
# - init -
pygame.init()
screen = pygame.display.set_mode((800, 600))
# - objects -
curr_time = pygame.time.get_ticks()
# first time check at once
check_time = curr_time
# - mainloop -
clock = pygame.time.Clock()
running = True
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# - updates -
curr_time = pygame.time.get_ticks()
if curr_time >= check_time:
print('time to check weather')
# TODO: run function or thread to check weather
# check again after 2000ms (2s)
check_time = curr_time + 2000
# - draws -
# empty
# - FPS -
clock.tick(30)
# - end -
pygame.quit()
BTW: if fetching web content takes more time then run it in thread.

furas
- 134,197
- 12
- 106
- 148