How to have json refresh on a schedule

  • 1
  • Question
  • Updated 2 years ago
Hello,

I am building a program that displays weather data on an LCD screen. It also lights up LEDs depending on weather conditions. Here's the problem I'm having:

Whenever I run my program it constantly pulls from the imported json file I made and I overuse my calls for the day (ok, I actually overuse my calls for the minute). How can I have my file with the json/API/Key/etc set to only refresh on a schedule?

If I use time.sleep(60) my main program just stalls and never actually calls the data. I've also tried a loop where it will call once then loop refreshing every 15 minutes - that didn't work either.

I've spent a few days researching this online and I can't find a suitable solution. I'm using python.

Thank you!
Catherine

Here is my program that I am importing into the main one (I have no idea how to post code boxes in a web forum - sorry in advance). I import this program, named api.py, into my main one. I also import all of the "location", "full_temp", etc along with it. The program works... it just does it too frequently.


import urllib2
import json
import time


while True:
    
    f = urllib2.urlopen('http://api.wunderground.com/api/XXXXXXXXXXX/geolookup/conditions/forecast/q/gb/brandon.json')
    json_string = f.read()
    parsed_json = json.loads(json_string)

    location = parsed_json['location']['city']
    full_temp = parsed_json['current_observation']['temperature_string']
    temp_f = parsed_json['current_observation']['temp_f']
    weather = parsed_json['current_observation']['weather']
    relative_humidity = parsed_json['current_observation']['relative_humidity']
    feels_like = parsed_json['current_observation']['feelslike_f']
    wind_dir = parsed_json['current_observation']['wind_dir']
    wind_mph = parsed_json['current_observation']['wind_mph']

    today_fcst = parsed_json['forecast']['txt_forecast']['forecastday'][0]['fcttext']
    tonight_fcst = parsed_json['forecast']['txt_forecast']['forecastday'][1]['fcttext']
    tomorrow_fcst = parsed_json['forecast']['txt_forecast']['forecastday'][2]['fcttext']
    today_pop = parsed_json['forecast']['txt_forecast']['forecastday'][0]['pop']
    today_high = parsed_json['forecast']['simpleforecast']['forecastday'][0]['high']['fahrenheit']
    today_low = parsed_json['forecast']['simpleforecast']['forecastday'][0]['low']['fahrenheit']
    today_outlook = parsed_json['forecast']['simpleforecast']['forecastday'][0]['conditions']
    
    f.close()
    
Photo of Catherine

Catherine

  • 1 Post
  • 0 Reply Likes
  • Frustrated

Posted 2 years ago

  • 1
Photo of Brandon

Brandon

  • 29 Posts
  • 7 Reply Likes
Instead of using the sleep command, could you schedule the job with cron (or the windows equivalent) to run every 15 minutes?