This.entity_id and last_triggered template

I am trying to limit an automation to running only once every 3 minutes
max (input_number.camera_cooldown)

condition:
  - condition: template
    value_template: >-
      {{ not state_attr('this.entity_id','last_triggered') or (now() -
      state_attr('this.entity_id','last_triggered') >
      timedelta(minutes=int(states('input_number.camera_cooldown')))) }}

When I run a trace, this seems to alwayts return true. Any ideas what I am doing wrong?

Remove the quotes around this.entity_id

Hi ohnoes4096,

You could also set the automation to single mode, and add a 3 minute delay at the end of it that it has to do before it’s done.

As Chris said, you need to remove the quotes. However, I’d also add that it’s not advisable to look up the object in the states table; instead the trigger object is already provided and you can access the parameter directly: this. attributes.last_triggered

I’m also not sure what the intention of the first not statement is.

This is the statement I recommend when someone wants a cooldown and doesn’t want to use a delay at the end of the automation (which is fine for short cooldowns).

{{ now() - this.attributes.last_triggered | default(0 | as_datetime) >= timedelta(hours=6) }}
1 Like

The not statement was to capture the first occurrence of the automation when it says “never” as last trigger time. Thank you mekaneck, I will use that.

@mekaneck has the correct answer. Lots of other examples have overly convoluted solutions as they mentioned. All you need is this.attributes.last_triggered with exactly the code in their example. It’s what I have as well and works perfectly.

- condition: template
  value_template: "{{ now() - this.attributes.last_triggered > timedelta(minutes=3) }}"

Just FYI, when it says “never” because it hasn’t been run, it means the last_triggered attribute is not defined. Using not this.attributes.last_triggered will generate an error, so instead you can send it to the default filter which will prevent the error. This is why default appears in the code I recommended.

Got it, thanks!