How to ensure that a service is completely carried out?

I’m using the code below to turn off the backlight on all my switches.
Is there a way to do this without “repeat” and ensure they all shut down?

- repeat:
  sequence:
	- service: switch.turn_off
	  data: {}
	  target:
		entity_id: |-
		  {{ states.switch |
			 selectattr('entity_id', 'search', 'backlight_') |
			 selectattr('state', '==', 'on') |
			 map(attribute='entity_id') |
			 list }}
	- delay:
		seconds: 3
  while:
	- condition: template
	  value_template: |-
		{{ states.switch |
		   selectattr('entity_id', 'search', 'backlight_') |
		   selectattr('state', '==', 'on') |
		   map(attribute='entity_id') |
		   list | length > 0 }}
	- condition: template
	  value_template: "{{ repeat.index <= 10 }}"

If you want to “ensure” the switches are off, then you’re obligated to confirm they’re off. You can use a repeat like you did or a custom integration that’s designed to perform the same thing (I don’t have a link to it handy at the moment).

The alternative is to improve the reliability of your switches so you don’t need to double-check if they’re truly off.

Not exactly on topic here but if you are doing something that is not asycnchronous (waits for a success reply but might throw an exception or not success and make an automation fail), there is a “retry” HACS integration you might want to consider that is pretty handy - if you have something that is not reliable it is sometimes a handy workaround -

How about setting a flag when you have run this automation, and do something with timers that keep retrying until all are completed or sends you a notification if something does not turn off properly?

That’s the “custom integration” I mentioned in my previous post. It’s effectively the same thing as what is being done with a repeat.

The current code works for me, but I thought there might be a better solution.
Thank you all!