2014-10-27 64 views
0

我正在研究一個小概念驗證並使用python來說明這個想法。這個想法是程序將循環運行並檢查輸入。現在,如果輸入低於閾值,則會發送通知。但我試圖以4秒爲間隔限制通知。那就是我放棄邏輯或語法的地方。無論哪種方式它正在做一些意想不到的事檢查python中的條件後的重複性通知語句

1:繼續輸入0,它會顯示下面的閾值消息,直到它達到4秒標記,然後它只是在一行打印出消息4次。我希望他們每4秒後顯示一次。這個想法是(A)輸入可能在4秒內改變並且通知切換。 (B)我希望通知在每次腳本碰到條件時以4秒的重複次數進行提醒,如果weightIn < 0.5 ..如果它是真的,那麼通知從第一次起4秒後熄滅發送

對不起,如果我試着解釋它。我對python很新穎

import threading 
def main(): 
     while True: 
       weightIn = float(input("Get value: ")) 
       threshold = .5 

       def operation(): 
         if weightIn < 0.5: 
           #send notification at an interval of 4 sec 
           threading.Timer(4.0, operation).start() 
           print("Below weight threshhold...send notification") 
         else: 
           print("You are good") 

       if threshold is not None: 
        operation() 

main() 
+0

對於時間,我會建議投票和timeit,這是應導入的模塊。 timeit是模塊,也就是說。輪詢是一個概念。 – 2014-10-27 05:39:22

回答

1

首先避免在循環中聲明函數。然後問自己,如果一個對象不合適,因爲它正確地包含了狀態屬性。

但算法部分,它很簡單(如果我正確地理解問題...)。存儲上次通知的時間戳,如果超過4秒,則發送一個新的通知。在僞代碼:

last_notification_time = 0 
threshold = 0.5 
loop: 
    weighIn = get_new_value() 
    if weightIn < threshold: 
     time = get_time_in_seconds() 
     if (time > last_notification_time + 4): 
      last_notification_time = time 
      send_notification() 
    # actual processing 

在Python,它可能看起來像:

#import time 

def main(): 
    last_notification_time = 0 
    threshold = 0.5 
    while True: 
     weighIn = float(input("Get value: ")) 
     if weightIn < threshold: 
      cur_time = time.time() 
      if (cur_time > last_notification_time + 4): 
       last_notification_time = time 
       print("Below weight threshhold...send notification") 
     # actual processing 

main() 
+0

@ Serge--同意不在循環中聲明一個函數......令人尷尬的是我確實這樣做了。我看到你關於閱讀時間戳的觀點......完全有效!再次感謝您的指導。 – soum 2014-10-27 13:57:41