Search code examples
pythontimer

Asyncro wait for a timer to expire in Python


So, I come to C in embedded programming where there's the function HAL_SYSTICK_Callback which is executed on every clock tick. With it, knowing the CPU clock, you can create timers in a way like

t_1ms = 1

if(t_1ms)
   t_1ms--;

And in the main code check if if(!t_1ms) do something

Now, I would like to do something like this in Python where, at a certain point in the code I load a timer and then in another part of the code, I check if the timer is exprired.

While executing the code, the timer must count by its onw without blocking the main code.

I've see libraries like waiting but they all seem blocking.


Solution

  • As suggest by matszwecja, the use of time.monotonic() is more than sufficient for my use case

    import time
    
    start = time.monotonic()
    # code that does something
    end = time.monotonic()
    if end - start > 1:
       # check if more than 1 second has been spent
       # do something else