Search code examples
pythonmultithreadinginfinite-loop

How to use a function in python after certain amount of time only if a state is true?


Using python3, I want to run a function every 10 seconds. But the function will run again only if a variable is still "on". I'm simulating the on/off randomly using random.random function. If the value of random.random is less than 0.5 the variable y is on and if y is more than 0.5 it goes off. With threading.timer I'm seting the function to run every 10 seconds. For simplicity I just punt print("x") in the body of the function.

import threading
import random

def machine_on():
    threading.Timer(10.0, machine_on).start() #called every 10 seconds 
    print("x")

y=0        
if y < 0.5:  
    machine_on()
    y = random.random()
else:
    sys.exit()

After running these code my computer enters into an infinite loop. Do you know what's the problem with my code? How can I solve the problem?


Solution

  • import random
    import time
    
    def machine_on():
                print("x")
    y=0         
    while True:
        if y < 0.5:  
            machine_on()
            y = random.random()
            print(y)
            time.sleep(10) 
        else:
            break