When state for some time + ignore unavailable

Hi everyone :wave:

I’m trying to create an automation to turn off my coffee machine after it has been on for 3 hours.

However, I realized that if the device becomes unavailable before the 3-hour mark, the for: timer resets — so the automation never triggers unless the state stays on continuously.

I asked ChatGPT for suggestions, and while it offered workarounds (like using multiple automations or complex templates), they feel a bit overkill for something that seems like it should be simple.

Does anyone know of a cleaner or simpler way to handle this, maybe a way to tolerate brief unavailable states without resetting the timer?

Thanks in advance! :pray:

triggers:
  - trigger: state
    entity_id: switch.coffee
    to:
      - 'on'
      - unavailable
    for:
      hours: 3
actions: ...

Though that relies on it being unavailable for an uninterrupted 3 hours.

The other way is to store the time you turn on the coffee machine in an input_datetime + 3 hours. Then trigger on that time.

in your on automation:

actions:
  - action: switch.turn_on
    target:
      entity_id: switch.coffee
  - action: input_datetime.set_datetime
    target:
      entity_id: input_datetime.coffee_off_time # you have to create this helper
    data:
      time: "{{ now() + timedelta(hours=3) }}"

Trigger for your off automation:

triggers:
  - trigger: time
    at: input_datetime.coffee_off_time
actions:
  - action: switch.turn_off
    target:
      entity_id: switch.coffee

I use that method for running my dehumidifiers a set time. It is very reliable.

Very nice!

I will try it for sure. Thanks