Skip to content Skip to sidebar Skip to footer

Python If Condition True For X Amount Of Time

I would like to create a condition that only gets executed if a is True for more than 3 seconds. I would like it to work like this. if a == True for more than 3 seconds: dosomet

Solution 1:

If you want to check if the value hasn't change for 3 seconds.

import time
id_a_old = id(a)
time.sleep(3)
id_a_new = id(a)
if id_a_old == id_a_new: # assumes that a is initially true
   dosomething

Since bool type is immutable the object id changes if it gets changed.

If you want to check if is has changed after 3 seconds do the following. If any thread changes a within 3 seconds it will capture that.

import timetime.sleep(3)
if a:
   dosomething

Solution 2:

Simple solution (motivated from Marlon Abeykoon's solution):

     import time
     startTime = time.time()
     while a == True:
         endTime = time.time()
         #do other stuff
         if (endTime - startTime > 3):    
             print("Longer than 3 seconds")
             break

Solution 3:

import time 

a = True 

x = int(time.time())
xa = a


while1:

    if a == True and xa == a andint(time.time()) == x + 3:
        # dosomethingprint"A is True for 3 seconds"breakif(xa != a):
        # dosomethingprint"Value of alfa changed from %s to %s in less than 3 seconds" %(xa, a)
        break

Post a Comment for "Python If Condition True For X Amount Of Time"