drizzle
drizzle

Reputation: 21

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.

Upvotes: 1

Views: 2045

Answers (2)

noslenkwah
noslenkwah

Reputation: 1744

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

Upvotes: 2

ldmichae
ldmichae

Reputation: 46

It depends on how you are monitoring the runtime of your motor. For the sake of example, let's assume you have that value stored in a variable, slowdown_time

 #slowdown_time is the variable that stores the time it took for the motor to slow down.

 import time

 desired_interval = 30   #seconds

 sleep_time = desired_interval - slowdown_time

 #sleep for remaining time
 time.sleep(sleep_time)

Hope this is helpful!

Upvotes: 0

Related Questions