2017-02-13 21 views
0

我需要能夠在特定時間段後切換布爾值,而其餘代碼仍照常運行。代碼的主要部分發生了什麼取決於Bool的值。在特定的時間量後更改變量python

這是我的嘗試與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) 
+0

你能包含的代碼你迄今爲止最好的嘗試?如果有起始基礎,理解這個問題要容易得多。 – roganjosh

+0

那好嗎?我沒有一個最好的嘗試,沒有任何工作。 – ElanaLS

回答

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() 
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()在其它代碼的部分可贖回

+0

如何從類中獲取返回的值?對不起,我是新來的...我試圖打印TimedValue,這是我得到的: <__ main __。TimedValue實例在0x1049e33b0> – ElanaLS

+0

像他說的。 value = TimedValue(),然後在任何時候需要該值,則調用value()。 –

+1

事實上,即使使用'__call__'也有點矯枉過正。對於初學者恕我直言(my_timed_value.value),屬性會稍微容易掌握。 +1顯示如何回答需求,而不是如何執行多處理(避免XY問題)。 –