问题描述
我需要能够在特定的时间后切换布尔值,同时我的其余代码继续照常运行。 代码主要部分中发生的事情取决于Bool的值。
这是我在goodguy的建议下进行的尝试,但仍然无法正常工作。 当我打电话给班级时,“正在播放”会切换为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)
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()
如在其他代码部分可调用
2楼
您可以使用模块multiprocessing
的ThreadPool
类:
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()