2015-04-18 81 views
1

我正在使用python。我需要在n秒後執行一個操作,而另一個條件爲真。我不知道我是否應該使用一個線程或只是一個計時器:在n秒後做一個動作python

start_time = time.time() 
while shape == 4: 
    waited = time.time() - start_time 
    print start_time 
    if waited >= 2: 
     print "hello word" 
     break 

形狀總是變化(我在相機的Frants手指的數量) ,而它的4秒和2秒(如shape==4後和shape==4shape==4 很多時候)我需要做一個動作(這裏我只使用打印)。我怎樣才能做到這一點?

+0

這與OpenCV有什麼關係? – KSFT

+0

你想讓其他代碼繼續嗎? –

回答

0

如果我正確地解釋你的問題,你想要的東西發生 2秒鐘你的情況是真實的,但也有可能是你可能需要做的還有其他的事情,所以一些塊不理想。在這種情況下,您可以檢查當前時間的秒數是否爲2的倍數。根據循環中發生的其他操作,間隔不會是,恰好爲 2秒,但非常接近。

from datetime import datetime 

while shape == 4: 
    if datetime.now().second % 2 == 0: 
     print "2 second action" 
    # do something else here, like checking the value of shape 
0

穆建議,你可以睡與time.sleep當前進程,但你要創建一個新的線程,像這樣調用一個函數傳遞每五秒鐘,而不會阻塞主線程。

from threading import * 
import time 

def my_function(): 
    print 'Running ...' # replace 

class EventSchedule(Thread): 
    def __init__(self, function): 
     self.running = False 
     self.function = function 
     super(EventSchedule, self).__init__() 

    def start(self): 
     self.running = True 
     super(EventSchedule, self).start() 

    def run(self): 
     while self.running: 
      self.function() # call function 
      time.sleep(5) # wait 5 secs 

    def stop(self): 
     self.running = False 

thread = EventSchedule(my_function) # pass function 
thread.start() # start thread 

# you can keep doing stuff here in the main 
# program thread and the scheduled thread 
# will continue simultaneously