Unable to update states

Hello,

So I created a custom component that calls an API and sets custom states to be the values retrieved from that API.

The issue is that after the first run of this script, the states do not get updated with new values. I have to keep restarting home assistant to update the states.

I’m sure there is a better solution, but I cant figure it out. Any input is appreciated.

Edit:
Here is the code that retrieves and sets the state. It’s in init.py of a custom component. I created another automation in the UI to run this script at 12am each day. But the states are set on the first run only. They don’t get updated after that.

async def async_setup(hass, config):
    """Set up is called when Home Assistant is loading our component."""

    times = await hass.async_add_executor_job(get_times)

    def handle_times(call):
        """Handle the service call."""
        time1 = convertTime(times['time1'], 0)
        time2= convertTime(times['time2'], 0)


        """This sets the state in hass"""
        hass.states.set('input_datetime.time1', time1)
        hass.states.set('input_datetime.time2', time2)


    async def async_handle_times(call):
        await hass.async_add_executor_job(handle_times call)

    hass.services.async_register(DOMAIN, "times", handle_times)

    # Return boolean to indicate that initialization was successful.
    return True

def get_times():
    location = "xxxx"
    apiKey = "xxxx"
    url = "xxxx"

    req = Request(url)
    req.add_header('Accept', 'application/json')
    req.add_header('Content-Type', 'application/json')
    req.add_header('User-Agent', 'Mozilla/5.0 (X11; CrOS armv7l 13597.84.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.57 Safari/537.36')
    response = urlopen(req).read().decode('utf-8')
    jsonStr = json.loads(response)
    times = jsonStr['items'][0]

    return times


def convertTime(aTime, offset):
    aTime = datetime.strptime(aTime, '%I:%M %p')
    aTime = aTime + timedelta(hours=0, minutes=offset)
    aTime = datetime.strftime(aTime, '%H:%M')
    return aTime

Post a link to your code so this can be reviewed and therefore advice provided.

This might help although there are different approaches possible, you might want to focus on how the DataUpdateCoordinator works.
As Mark posted, it helps to post a link to the code…

I updated the post with the code I have. Any guidance to point me in the right direction is much appreciated

So what are you trying to achieve? Do you want it to update only on calling the service via an automation or every x minutes?

For updating when you call your service, you seem to be missing a call to get_times. This is only called when the integration is first loaded and never again. Put a call to this in handle_times.

Thank you! That fixed it gor me.