Run_in - logic to cancel if it's restarted

I have a hue switch that I use to trigger a lot of things based on the hue_event. In one case, I need to delay a couple actions for 30 seconds. So I use the run_in scheduler to call the function in 30 seconds. Pretty straight-forward.

But then there’s the case where someone pushes the button once. And then again say 15 sec later. Now there are two run_in calls scheduled, and the first one happens before the second one, which isn’t the desired behavior. I store the handle in a list as follows:

self.listen_run_in_handle_list.append(self.run_in(self.cb_run_in, 30))

So now I have the handle in the list, but I don’t necessarily know which one it is to cancel should the button get pressed again.

Does anyone know of an easy way to track this in the app so it can be canceled if the button is pushed again before it fires? I thought about using a dict with the key associated with the button, but that starts to get a bit complicated. It would be something like:

handle = self.run_in(self.cb_run_in, 30)
run_in_dict["hue_switch_button_4_long_press"] = handle

Maybe this is the solution, but looking for some other clever way to do this because I’d have to check if the handle is in the dictionary, if it is, then cancel the scheduled run_in, and then add the new handle to the dictionary…

You have definitely answered your own question. Using a dictionary with a unique key is the answer.

1 Like

Thanks for the confirmation!