Looping on condition button - Python

Hi All,

Raspberry Pi, Python environment.

I have multiple button widgets that manually control relays. All works just fine. I also read data from sqlite tables associated with these relays eg. name of node. I have another table with a daily schedule for each of these nodes. Want I need is another associated button (I call it a timer button) that toggles ON/OFF to use the manual button above or revert to the schedule.

This sort of works in that if the manual button is ON and the schedule says at that time it should be OFF if I press the Timer Button it corrects it and switches it OFF.

But the problem is it only works once when I press the Timer Button and doesn’t check it every time it loops.

What I want is if the Timer Button is ON it sets the relay to the schedule.
If the Timer Button is OFF it accepts manual button press.

Bear in mind this is all in Python !!

This is my code for the manual relay button

# register handler for virtual pin V4 write event
@blynk.handle_event('write V4')
def write_node1(pin, value):
    
    print "node #1", value
    GPIO.setup(int(pin1),GPIO.OUT)
    if value == [u'0']:
        GPIO.output(int(pin1),GPIO.LOW)
    if value == [u'1']:
        GPIO.output(int(pin1),GPIO.HIGH)

and this is my code for the Timer Button

#register handler for virtual pin V35 write event node 1
@blynk.handle_event('write V35')
def write_timer1(pin, value):
   

    print ('before test value', pin, value)
    if value == [u'1']:
         
        conn = create_connection(database)
        cur = conn.cursor()
        cur.execute("SELECT node, action, fromtime, totime FROM actions WHERE time('now', '+2 hour') >= fromtime AND time('now', '+2 hour') < totime AND node = 1")
       
        rows = cur.fetchall()

        for row11 in rows:
            action1 = row11[1]
            
        GPIO.setup(int(pin1),GPIO.OUT)

        sstate1 = GPIO.input(int(pin1))
        
        print('node 1 just before state check', value, sstate1, action1)
        if sstate1 == 0 and action1 == 'ON':
            cur.execute("UPDATE nodes SET laststate = 'ON', date = date('now'), time = time('now', '+2 hour') WHERE node = 1")
            time.sleep(2)
            print('node 1 inside condition to switch on', pin, pin1, value, sstate1, action1)
            GPIO.output(int(pin1),GPIO.HIGH)
            blynk.virtual_write(4, 1)
            time.sleep(3)

        if sstate1 == 1 and action1 == 'OFF':
            cur.execute("UPDATE nodes SET laststate = 'OFF', date = date('now'), time = time('now', '+2 hour') WHERE node = 1")
            time.sleep(2)
            print('node 1 inside condition to switch off', pin, pin1, value, sstate1, action1)
            GPIO.output(int(pin1),GPIO.LOW)
            blynk.virtual_write(4, 0)
            time.sleep(3)