簡體   English   中英

在n秒后執行操作python

[英]do an action after n seconds python

我正在使用python。 我需要在n秒鍾后執行一項操作,而另一個條件為true。 我不知道應該使用線程還是僅使用計時器:

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

當形狀為4時,形狀總是變化(我的手指在相機中的手指數),並且在2秒后(例如, shape==4shape==4shape==4很多次),我需要執行一個操作(這里我只使用打印)。 我怎樣才能做到這一點?

如果我正確地解釋了您的問題,則您希望 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

正如Mu所建議的,您可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM