Can't get my automation to trigger every 2 hours

I am trying to run a automation where every 2 hours it turns on, wait 1 hour, turn off. Then the trigger should happen again in 2 hours but it never did. This is what I got so far:

alias: Pet fountain
description: ''
trigger:
  - platform: time_pattern
    hours: '2'
condition: []
action:
  - type: turn_on
    device_id: efa075ce528e125e51524d77850f7526
    entity_id: switch.plants_humidifier_2
    domain: switch
  - delay:
      hours: 1
      minutes: 0
      seconds: 0
      milliseconds: 0
  - type: turn_off
    device_id: efa075ce528e125e51524d77850f7526
    entity_id: switch.plants_humidifier_2
    domain: switch
mode: single
trigger:
  - platform: time_pattern
    hours: '/2'

Don’t use long delays…

Create a timer helper then use that instead. There are simpler methods to achieve your goal, but the following allows for changing the on and off times and lets you pause and restart the cycle easily by cancelling or restarting the timer.

trigger:
- platform: event
  event_type: timer.finished
  event_data:
    entity_id: timer.humidifier_switch
condition:
action:
- variables:
    on_time: "01:00:00"
    off_time: "01:00:00"
    next_interval: >
      {{ on_time if is_state('switch.plants_humidifier_2', 'off') else off_time }}
- service: switch.toggle
  target:
    entity_id: switch.plants_humidifier_2
- service: timer.start
  data:
    duration: "{{ next_interval }}"
  target:
    entity_id: timer.humidifier_switch

I’m getting this message when trying to use your code:

Message malformed: invalid template (TemplateSyntaxError: invalid syntax for function call expression) for dictionary value @ data['action'][0]['variables']['next_interval']

My bluetooth keyboard is dumb sometimes… the = should have been a ==… I have fixed it above.

It still gives me the error:

Message malformed: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['action'][0]['variables']['next_interval']

Turns on for an hour, then turns off for an hour. Repeat, ad infinitum.

alias: Pet fountain
description: ''
trigger:
  - platform: time_pattern
    hours: '/1'
condition: []
action:
  - service: switch.toggle
    target:
      entity_id: switch.plants_humidifier_2
mode: single
1 Like

Thanks, that worked!

1 Like

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. This helps users find answers to similar questions.

For more information about the Solution tag, refer to guideline 21 in the FAQ.

1 Like