1

I'm working with python. I need to do an action after n seconds while another condition is true. I don't know if I should use a thread or only a timer:

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

The shape is always change (the number of my finger in Frants of camera) while it's 4 and after 2 seconds (like shape==4 and shape==4 and shape==4 many time) I need to do an action (here I use only print). How can I do this?

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186

2 Answers2

0

If I'm interpreting your question correctly, you want something to happen every 2 seconds while your condition is true, but there may be other things you might need to do as well, so something that blocks isn't ideal. In that case, you can check if the seconds value of the current time is a multiple of 2. Depending on the other actions happening in the loop, the interval won't be exactly 2 seconds, but pretty close.

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
1.618
  • 1,765
  • 16
  • 26
0

As Mu suggested, you can sleep the current process with time.sleep but you want to create a new thread like so that calls a passed function every five seconds without blocking the main thread.

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
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70