Automation: repeat until some time has elapsed

Hello,

In order to be sure that an MQTT order is being sent and received, I would like to configure an automation to send the instruction until the desired state is reached or until a specific duration is reached (to avoid sending the instruction forever in case of serious issue).

I know that I can specify a specific time to stop the repeat loop, but I would prefer to specify it with a duration (like 10 minutes).

Here is my automation:

- id: '123456798'
  alias: Turn on
  description: ''
  trigger:
  - platform: time
    at: 15:00
  condition: []
  action:
  - repeat:
      until:
      - condition: state
        entity_id: climate.heater
        state: heat
      sequence:
      - service: climate.turn_on
        data: {}
        target:
          entity_id: climate.heater
      - delay:
          hours: 0
          minutes: 0
          seconds: 10
          milliseconds: 0
  mode: single

Does someone know how I can limit the “repeat until” to 10mn duration ?

Thanks a lot in advance

  action:
  - repeat:
      until: "{{ is_state('climate.heater', 'heat') or repeat.index == 60 }}"
      sequence:
      ... etc ...

Your repeat employs a 10-second delay per iteration. 60 iterations times 10 seconds equals 600 seconds (10 minutes). So by the 60th iteration, ten minutes have passed.

3 Likes

Nice trick, thanks !
but just out of curiosity, is there no mechanism to be able to put a condition on time elapsed ?

You can also do it like this:

  action:
  - variables:
      stop_time: "{{ now() + timedelta(minutes=10) }}"
  - repeat:
      until: "{{ is_state('climate.heater', 'heat') or now() >= stop_time }}"
      sequence:
      ... etc ...
2 Likes

Very interesting trick, I learnt a lot today, thanks.

I also wanted to flash a light, to try and locate mystery devices. I had to modify with as_timestamp, adding here for anyone else trying in late 2023:



- id: 45672323f329532323
  alias: flash_light
  description: "Flash_Light"
  trigger:
  condition: []
  action:
    - variables:
        stop_time: "{{ now() + timedelta(minutes=10) }}"
    - repeat:
        sequence:
          - service: light.toggle
            target:
              entity_id: light.office_lamp
            data: {}
          - delay:
              hours: 0
              minutes: 0
              seconds: 2
              milliseconds: 0
        until:
          - condition: template
            value_template: "{{  as_timestamp(now()) >= as_timestamp(stop_time)
              }}"
    - service: light.turn_off
      target:
        entity_id: light.office_lamp
      data: {}
  mode: single

1 Like