仅当状态为真时,如何在一定时间后使用 python 中的函数?

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

使用 python3,我想每 10 秒 运行 一个函数。但是只有当变量仍然是 "on" 时,函数才会再次 运行。我正在使用 random.random 函数随机模拟 on/off。如果 random.random 的值小于 0.5,则变量 y 打开,如果 y 大于 0.5,则关闭。使用 threading.timer,我将函数设置为每 10 秒 运行。为简单起见,我只是在函数体中输入 print("x")

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()

在 运行 执行这些代码后,我的计算机进入了无限循环。你知道我的代码有什么问题吗? 我该如何解决这个问题?

你可以在线程中完成

def print_x():
   global y
   for i in xrange(1000000): # or use while True
      if y > 0.5:
          print('x')
      time.sleep(10)
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