How do I turn off the triggering light from a list of lights after a designated period of time?

Hi. I’m a n00b. This is my first post!

I have a whole bunch of lights around my house I want to put on a timer. I want to put them in a list and trigger with a single automation.
Timer goals:

  1. Should be durable through resets of Home Assistant. Even if the HA resets, I want to still turn off the light after 5 minutes
  2. Should use just one automation instead of many separate automations
    Is this possible?

Here’s a simple example of what I’d like to do:
Trigger:

entity_id: 'switch.amber_closet_switch, switch.adam_closet_switch_2'
platform: state
to: 'on'
for: 
  seconds: 5

Action:

domain: switch
entity_id: {{trigger.device}}
type: turn_off

I’ve tried several variations and I can’t seem to get it to work. I also can’t find good examples of how to use templates within actions. Any help would be much appreciated!

That just made it a whole lot harder! It’s possible (or, at least, it’s possible to have them turn off at least 5 minutes later, since HA can’t do much if it’s not running when the time rolls around), but it would take a lot more work. How often do you think it’s likely to happen that HA restarts during one of these 5 minute periods?

Without that requirement, it’s a cinch:

- trigger:
  - platform: state
    entity_id:
    - switch.amber_closet_switch
    - switch.adam_closet_switch_2
    to: 'on'
    for:
      minutes: 5
  action:
  - service: switch.turn_off
    data_template:
      entity_id: "{{ trigger.entity_id }}"

See here for documentation on the trigger variable fields corresponding to a state trigger.

1 Like

Thanks @pnbruckner. I appreciate it. That worked well!

I’m converting my house over to HA from SmartThings. I wrote a SmartApp in SmartThings to turn off my pool filler after 30 minutes. It would track the state of the device to say “if the valve is on for more than 30 minutes, then turn it off”. I’m just worried about this sort of thing on home assistant because it’s running on a raspberry pi instead of in the cloud.

I suppose I’ll have to deal with a timer restart on home assistant restart?

Is there a way to check if the last time the device was off is longer than 5 minutes ago?

If you absolutely need to survive a restart, then the typical way to do that is to use an input_datetime to record the date/time the device is switched on, and then use a template trigger to compare that to sensor.date_time. Unfortunately sensor.date_time's state isn’t directly usable, so as a hint:

- trigger:
  - platform: template
    value_template: >
    {{ states('sensor.date_time').replace(',', '')|as_timestamp >
       state_attr('input_datetime.XYZ', 'timestamp') }}