Search code examples
pythonsleep

Sleep until a certain amount of time has passed


I'm writing a function in Python that waits for an external motor to finish moving, but the amount of time it takes for the motor to move can be variable. I want to standardize the time in between each move — for example, they should all take 30 seconds.

Is there a way to implement a sleep function so that it sleeps the required amount of time until 30 seconds has passed?

For example: if the motor takes 23 seconds, the function will wait until 30 seconds have passed, so it will sleep 7 seconds.


Solution

  • It sounds like don't want to sleep for 30 second but rather pad the time it takes to perform an activity with a sleep so that it always takes 30 seconds.

    import time
    from datetime import datetime, timedelta
    
    wait_until_time = datetime.utcnow() + timedelta(seconds=30)
    move_motor()
    seconds_to_sleep = (wait_until_time - datetime.utcnow()).total_seconds()
    time.sleep(seconds_to_sleep)
    

    if you are going to be doing this in multiple places you can create a decorator that you can apply to any function

    import functools
    import time
    from datetime import datetime, timedelta
    
    def minimum_execution_time(seconds=30)
        def middle(func)
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                wait_until_time = datetime.utcnow() + timedelta(seconds=seconds)
                result = func(*args, **kwargs)
                seconds_to_sleep = (wait_until_time - datetime.utcnow()).total_seconds()
                time.sleep(seconds_to_sleep)
                return result
            return wrapper
    

    You can then use this like so

    @minimum_execution_time(seconds=30)
    def move_motor(...)
        # Do your stuff