Search code examples
pythonpython-3.xfunctionmethodsauto-update

Python auto-update function


I'm writing this code for a project, and I have this class which parses the Weather from OWM. My code for this section looks like this:

class Meteo():
    def __init__(self):
        self.API = pyowm.OWM('My API Key', config_module=None,
                             language='it', subscription_type=None)
        self.location = self.API.weather_at_place('Rome,IT')
        self.weatherdata = self.location.get_weather()
        self.weather = str(self.weatherdata.get_detailed_status())

    def Temperature(self):
        self.tempvalue = self.weatherdata.get_temperature('celsius')
        temperature = str(self.tempvalue.get('temp'))
        return temperature

The problem is, of course that, by running the program at 2 pm, and it's 20°C, by 2am it would still show the same temperature, because (obviously)it stays the temperature it parses at launch. I've searched the web for auto updating a python function but I didn't find a question explaining my case. If someone could answer or point out to me a place where it is explained, I would be very grateful. Thanks


Solution

  • In general, there is no magic going on. If you need current data, you will need to fetch it.

    There are many conditions you could choose to trigger the 'data update' e.g., if you are processing the data in some form or on a schedule.

    If it is sufficient in your use-case to fetch the current temperature on an hourly basis, it sounds like some form of a cron job would solve your problem. The whole point of a cron job is to execute tasks on a preset schedule. Checkout Wikipedia.

    Maybe the link from Aaron_ab (How do I get a Cron like scheduler in Python?) fits best in your scenario. Or perhaps take a look at Celery Beat.

    If you do not need your application running the entire time, it might be best to use cron on your OS and let it execute your application whenever it is necessary.