【问题标题】:do an action after n seconds python在 n 秒后执行一个动作 python
【发布时间】:2015-04-18 20:27:24
【问题描述】:

我正在使用 python。当另一个条件为真时,我需要在 n 秒后执行一个操作。我不知道我应该使用线程还是只使用计时器:

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==4shape==4shape==4 很多次)我需要做一个动作(这里我只使用打印)。我该怎么做?

【问题讨论】:

  • 这和 OpenCV 有什么关系?
  • 你想让其他代码继续吗?

标签: python time timing


【解决方案1】:

如果我对您的问题的解释正确,您希望在您的条件为真时 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

【讨论】:

    【解决方案2】:

    正如 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多