0

I have video processing code that communicates with plc. Inside a infinite while loop i need a timer/counter to execute a command. The code looks like this:

while True: 
    if(condition1): 
        #do something

    elif(condition2): 
        #do another thing

    elif(condition3): 
        #do another thing

    elif(condition_10s_passed): 
        print("You have waited too long")

Here i couldn't implemet time.sleep() from time or root.after() from tkinter since they stop the while loop which i don't want.I checked threading.timer() but couldn't implemented it either.

I use pose detection algorithm from mediapipe, and show the video on a screen. Also i have found a solution but it caused a fps drop in the video so i am asking for a better solution.

My solution is like this: I defined the old_timeeverywhere except inside the elifin which i check the condition for time passed. Then i take difference between current time with old_time to measure time passed.

while True:
    old_time=time.time() 

    if(condition1): 
        old_time=time.time()
        #do something 

    elif(condition2): 
        old_time=time.time()
        #do another thing

    elif(condition3): 
        old_time=time.time()
        #do another thing

    elif (time.time()-oldtime)>10: 
        print("You have waited too long")

The reason for fps drop may be something else, but it started after i implemented this solution. I am not an expert on optimized codes i need to know if fps problem is not due to too many old_time definitions.

Note: This is my first question i am open to the comments about my question (its title,content, definition, etc.)

  • You need to add a sleep in the loop, or else there will be a Gazillian clock reads. But obviously a signal from the OS is better--check out https://stackoverflow.com/questions/492519/timeout-on-a-function-call – Andrew Sep 06 '21 at 10:43

1 Answers1

0

I found a solution. I used time.sleep() but in another thread to not to interrupt while loop.

#5 seconds timer
def timer():
   global limit_time
   limit_time = False
   time.sleep(5)
   limit_time = True

#Starting the timer in another thread when condition is satisfied
if("condition to start timer"):
   thread1 = Thread(target=timer)
   thread1.start()

Here when the condition is satisfied timer function is called which waits 5 seconds then changes the varaible limit_time to True. Then in the code i know that 5 seconds passed by checking the variable limit_time.