Search code examples
pythontimer

How to make Non-blocking timer in Python


i need your help.

I need a non-bloking timer, that allows me, in the period it's still counting, doing other tasks. I need this function for my bot and obviously I don't want to block it all times I call this type of function which requires these timers.

So, in the past i used to use in Arduino (c++) the function millis() that in the same configuration seems not working well like

int t0 =0
int t1

void loop(){
t1= millis()
while (t1-t0 < 6000){
Serial.print(Timer!);
t0 = millis();}}

Do you have any advice for me? A code where I can start from? Thanks!


Solution

  • Okay, i found the solution by myself, trying to remember what i previously did on Arduino.

    I based this answer from Adam Minas's one, but mine is quite different

    So the expected behavior had to be: print(something) every 5 seconds so:

    import time
    
    start_time = time.time() # returns number of seconds passed since epoch
    #current_time = time.time()
    print(start_time)
    max_loop_time = 20 # 6 seconds
    
    while True:
    
        while (time.time() - start_time) > max_loop_time:
        
                print("Timer")
                start_time = time.time()
    

    Then you can stop your while loop with break and other functions like

    if == smth : 
        break