Laura Smith
Laura Smith

Reputation: 313

Execute a method only when two seconds have elapsed from last execution time

I have a while loop which executes two methods. I want the functionB() to execute only EVERY 2 seconds. I know there are solutions which can use the thread to use a timer to execute it every two seconds, but that is something that I DO NOT want to use. I want both methods to run on the MAIN thread.

def functionA():
   # Code goes here

def functionB():
   # Code goes here

while True:
        # Execute function A
        functionA() 

        # Periodically execute functionB every 2 seconds
        functionB()

I am not sure on how to calculate the difference between the last time it executed and the current time. I search online for a few examples but they seem to confuse me more.

Any help would be appreciated.

Upvotes: 0

Views: 180

Answers (1)

Standard
Standard

Reputation: 1512

get the timestamp in seconds and check if 2 or more seconds have passed since the last execution.

import time    
def functionA():
   # Code goes here

def functionB():
   # Code goes here
lastExec = 0
while True:
        # Execute function A
        functionA() 

        now = time.time()
        if now - lastExec >= 2:
           # Periodically execute functionB every 2 seconds
           functionB()
           lastExec = now

Upvotes: 1

Related Questions