Changing the run time that a callback is triggered

I want to use an input_datetime to define the time a callback is triggered.
Since the initialize function will set the callback function to run at the time input_datetime was at the time the function is called, how would i update the callback time dynamically?

Thanks!

Set the time according to your input_datetime in the initialize function. Then listen for state change for your input_datetime, cancel the current callback, add a new one whenever the input_datetime is changed.
So, apart from what you already have, you would need to add:

# In the initialize function:
self.callback_handle = run_at... #Your run function goes here.
self.listen_state(self.update_callback_time, "input_datetime.your_datetime")

def update_callback_time((self, entity, attribute, old, new, kwargs):
  # Cancel the current timer:
  cancel_timer(self, self._callback_handle)
  ## Add code to update the run function.
  self.callback_handle = run_at... #Your run function goes here.
import hassapi as hass
import datetime
import time

#App to turn on lights gradually
#Args:
#time: the time at which we want to turn the light on
#light: the light we want to turn on

class WakeUpLights(hass.Hass):
    def initialize(self):
        self.light = self.args["light"]

        time_entity = self.args["time"]
        time = self.get_state(time_entity)

        self.callback_handle = self.run_daily(self.wake_up, time)
        self.listen_state(self.update_callback_time, time_entity)

    def wake_up(self, kwargs):
        self.turn_on(self.light,brightness=20, color_temp = 500)
        for i in range(40,255,20):
            self.turn_on(self.light,brightness=i, color_temp = 500)
            time.sleep(120)

    def update_callback_time(self, entity, attribute, old, new, kwargs):
        self.cancel_timer(self.callback_handle)
        self.callback_handle = self.run_daily(self.wake_up, new)

Thanks! works perfectly. It also helped me to understand how the callbacks work better.
One last thing, i saw in the docs that you should not use time.sleep() so as not to tie up the thread.
In this case would recursion with run_in() work well?

Thanks again for your help

Great that you got it working! You should look into using async programming in the appdaemon docs. Then you can use asyncio.sleep, but yes, recursive run_in would work.

Here is more on async: https://realpython.com/async-io-python/

As it is now, the time.sleep(120) call will block the running thread.

1 Like

I will definitely do that!.
Thanks again for all your help.
Much appreciated