Force template sensor to update periodically

Heya,

I have a few template sensors for power that basically return a fixed power whenever a given equipment is on. However, as the value is not changing, the sensor can go for hours without updating, which messes up a ton of things (namely, my grafana plots :wink: ).

I’d like to have the sensor update every minute and generate a new datapoint, but I cannot find a clean way to do it. I tried having an automation force the sensor to re-evaluate, but this doesn’t seem to update it. Then I a setup a boolean helper that flips every minute and just used it to set up a variable inside the template, but if this doesn’t change the value it doesn’t seem to work either. The only way I could make it update was to add a very small value if this helper is on, which works but is kind of a shitty way to do it. Any idea how to do this cleanly?

This is my current definition:

  - name: power_heater_livingroom_template
    unique_id: power_heater_livingroom_template
    device_class: power
    unit_of_measurement: W
    state: >
        {% set tick = states('input_boolean.minute_tick') %}
        
        {% if tick == 'off' %}
          {% if is_state('binary_sensor.z2m_climate_w500_livingroom_template_heating', 'off') %}
            0
          {% else %}
            3950
          {% endif %}
        {% else %}
          {% if is_state('binary_sensor.z2m_climate_w500_livingroom_template_heating', 'off') %}
            0.000000001
          {% else %}
            3950.000000001
          {% endif %}        
        {% endif %}

Thanks!

An easier way would be to add now() to your template to force it to update every minute. Then just add a small random amount + range(-10, 10) | random /1000

Thanks for the tip, it is indeed a more elegant approach.

Still, I feel like this is an ugly workaround to achieve something that should be quite simple :sweat_smile:

What you are trying to accomplish is something that HA works hard on preventing.
Unnecessary writes to the database.
If the value is the same then don’t update.
You are literally trying to combat how HA is designed

Indeed, but there are relevant use cases for it and it’s something very common in the field I come from (Industrial Automation).