Limit automation triggering

I just wanted to share a basic recipe for when you want a trigger to work at most once every X minutes (or whatever time is needed), for instance to limit notification spam.

The idea is simple: in the action part, just disable the automation from itself, do your things, add a delay as needed and finally enable the automation again.

automation:
  - alias: Test
    trigger:
      # Your trigger
      - platform: state
        entity_id: input_boolean.testbool
        to: 'on'
    action:
      # Disable this automation
      - service: automation.turn_off
        entity_id: automation.test
      # Do stuff
      - service: homeassistant.toggle
        entity_id: switch.some_switch
      # Wait some time and turn the automation back on
      - delay:
          minutes: 1
      - service: automation.turn_on
        entity_id: automation.test

Nothing strange once you know about it, but that you can disable and enable the automation from within itself might feel counter-intuitive, so I thought I’d share this.

27 Likes

So, to make sure I’m clear: when you turn off an automation, that just prevents it from triggering again, but let’s the instance that’s already running complete it’s action?

Yes, precisely. :slight_smile:

2 Likes

Just to add my 2c this is probably also a good thing in conjuction with the wait_template which lets you wait for a specific state.

~Cheers

2 Likes

I wonder if limiting could be added as a condition?

Just a side note: I don’t think the wait_template actually works.

1 Like

Just letting anyone else trying this out know that a script will work better for the sequencing of turning off and on the automation.

This can cause an integrity issue if you Home Assistant is shut down during your delay. Then on the next start, your automation will be permanently off.

Better to use a condition like this:

condition:
    - condition: template # only notify once every hour at most
      value_template: "{{ ( as_timestamp(now()) - as_timestamp(state_attr('automation.notify_me', 'last_triggered')) |int(0) ) > 3600 }}"
7 Likes

With the new update, this is now done by setting the automation mode to single (already the default) and adding a delay to the end of however long you want minimum between the automation triggers.

5 Likes

Not working that way for me. Maybe updates since your post have changed the behaviour?
My experience is that after the service automation turn off, nothing else executes and the automation turn on never happens after the delay.

Thank you, this works great!
(I’m Limiting the number of times an automation runs to update text overlay on a CCTV cam via it’s API).

1 Like