Help with Automation please: how to perform a task until specific sensor value is met

I need some help setting up a (what i thought to be a) simple automation:

I’ve got a relay and a sensor. and all i want is when a button is pressed, to check the sensor, and if the value is above a certain point to switch teh relay on and then leave it on until the certain point is met.

now, i got as far as getting the relay to be switched on after checking the value, but then i don’t know how to turn it off again after the value is met.
I tried is with a “while” and a “wait_until” action, but then it seems to switch the relay on and on and on again. (supposedly until the value is met, but i never get this far because then the logs throw an error that the esp node disconnected from the api and the relay is switched off…)

Please point me in the right direction for a solution.

Here’s what I have so far (which doesn’t work):

sensor:
  - platform: vl53l0x
    name: "Distance1"
    address: 0x29
    update_interval: 500ms
    long_range: true
    id: distance1

button:
  - platform: template
    name: "desk-standing"
    id: desk_standing
    on_press:
      then:
        - if:
            condition:
              lambda: 'return id(distance1).state < 0.24;'
            then:
              - switch.turn_on: relay_up
              - wait_until:
                  lambda: |-
                    (return id(distance1).state = 0.24);
              - switch.turn_off: relay_up    
  - platform: template
    name: "desk-sitting"
    id: desk_sitting
    on_press:
      - while:
          condition:
            lambda: |-
              return id(distance1).state > 0.09;
          then:
          - switch.turn_on: relay_down

Create another automation to turn it off when the value is met.

thank you for the quick response.
“where” would i create this automation? can’t do it as an on_press for the button, because it has to check continuously until the value is met, not just once after the button-press.

Should i implement it in the sensor? how? I tried this:

sensor:
  - platform: vl53l0x
    name: "Distance1"
    address: 0x29
    update_interval: 500ms
    long_range: true
    id: distance1
    on_value:
      then:
        if:
          condition:
            lambda: 'return id(distance1).state < 0.24;'
          then: 
            - switch.turn_off: relay_up
            - switch.turn_off: relay_down
          else:
            if:
              condition:
                lambda: 'return id(distance1).state < 0.1;'
              then:
                - switch.turn_off: relay_down
                - switch.turn_off: relay_up

…but that ofc doesn’t work, because it now always checks for said values and not just after the button is pressed and the relays are turned off all the time.

any further help would be appreciated