我需要能够在特定时间后切换布尔值,而其他代码继续像往常一样运行。在代码的主要部分中发生的事情取决于Bool的值。
这是我对goodguy的建议的尝试,但我仍然无法让它工作。当我打电话给班级时,'playing'切换到True,但是在2秒后没有切换回False,所以音调只播放一次。我做错了什么?
class TimedValue:
def __init__(self):
self._started_at = datetime.datetime.utcnow()
def __call__(self):
time_passed = datetime.datetime.utcnow() - self._started_at
if time_passed.total_seconds() > 2:
return False
return True
playing = False
while True:
trigger = randint(0,10) # random trigger that triggers sound
if trigger == 0 and playing == False:
#play a tone for 2 seconds whilst the random triggers continue running
#after the tone is over and another trigger happens, the tone should play again
thread.start_new_thread(play_tone, (200, 0.5, 2, fs, stream,))
value = TimedValue()
playing = value()
time.sleep(0.1)
答案 0 :(得分:1)
对于这种情况,线程和多处理听起来有点过分。另一种可能的方法是定义类似可调用类的内容,其实例会记住为测量创建的时间:
import datetime
class TimedValue:
def __init__(self):
self._started_at = datetime.datetime.utcnow()
def __call__(self):
time_passed = datetime.datetime.utcnow() - self._started_at
if time_passed.total_seconds() > XX:
return True
return False
value = TimedValue()
以及在代码的其他部分使用value()
作为可调用对象时
答案 1 :(得分:0)
您可以使用模块ThreadPool
中的multiprocessing
类:
import time
myBool = False
def foo(b):
time.sleep(30) #time in seconds
return not b
from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)
result = pool.apply_async(foo,[myBool])
b = result.get()