How can I make a button to turn off lights/activate a scene after a 20 minute delay

Apologies if this has been answered, I’ve searched and searched and can’t quite find my answer.

I have a group of lights in my bedroom (or I could create a scene), I want to be able to press a dashboard button that will wait 20 minutes, then turn them off. This is basically so I can put my phone down and not have to pick it up again to turn off the lights before going to sleep.

Can anyone advise how I could do this, please? I’ve attempted a couple of ways but can’t make it work.

Use a script:

script:
  bedroom_delayed_lights_off:
    sequence:
      - delay:
          - minutes: 20
      - service: light.turn_off
        target:
          entity_id: light.bedroom_lights

Assign this script to a button tap action:

type: button
name: Delayed Bedroom Lights Off
show_state: true
entity: script.bedroom_delayed_lights_off
icon: "mdi:bed-clock"
tap_action:
  action: call-service
  service: script.bedroom_delayed_lights_off

The advantage of doing it this way is that it is relatively simple.

There is a minor disadvantage with this method if home assistant is restarted while the script is waiting in the delay. The script will be cancelled and the light will not turn off.

This seems unlikely to happen as you will be in bed and not messing around restarting home assistant.

If for some reason you think this is a likely scenario you would have to use a timer as they can be restored after a home assistant restart (as long as they don’t finish while home assistant is shut down).

this can be solved by calling the script at HA startup using an automation with this trigger:

    - platform: homeassistant
      event: start

Not really. It will just restart the timer. So worst case the light could be on for 40 minutes.

If it is going to be an issue (I really don’t think it will be) a timer would be the way to go.

This is brill, thank you! You’re right about me being unlikely to be restarting HA while I’m dozing off so not an issue.

Do I just paste that wholesale into the yaml editor in the scripts tab? I’m getting “Message malformed: extra keys not allowed @ data[‘script’]” when I try to save.

Don’t include the first line script: if using an !include in your configuration.yaml file.

This:

script: !include scripts.yaml

Would end up resolving to:

script:
  script:  ###### <---------------------- WRONG
    bedroom_delayed_lights_off:
      sequence:
        - delay:
            - minutes: 20
        - service: light.turn_off
          target:
            entity_id: light.bedroom_lights

Instead of:

script:
  bedroom_delayed_lights_off:
    sequence:
      - delay:
          - minutes: 20
      - service: light.turn_off
        target:
          entity_id: light.bedroom_lights