-1

I need code that will do this:

def foo():
  now = datetime.datetime.utcnow()

  # Some code will run that takes a variable amount of time
  # (less than 15 minutes)

  # This code should run no sooner than 15 minutes after `now`

Note that this is not the same as using time.sleep! time.sleep would halt the entire process, but I need computation in foo() to happen and for foo() to return no sooner than 15 minutes after it begins.

Richard
  • 56,349
  • 34
  • 180
  • 251
M. Koz
  • 41
  • 3

3 Answers3

0

You need to calculate the time between the current time and the desired restart time. Then sleep for that amount of time.

wait_time = 15 # minutes

restart_time = datetime.datetime.now() + datetime.timedelta(minutes=wait_time)

# execute code that takes a long time
# for example, let's just sleep for some time
random_time = random.randint(1, wait_time)
time.sleep(random_time * 60)


print("See you again at ", restart_time)

# Now, calculate how long you need to sleep to resume at restart_time
sleep_time = restart_time - datetime.datetime.now()

# Sleep for that amount of time
time.sleep(sleep_time.total_seconds())
print("Hi, I'm back ", datetime.datetime.now())
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
0

datetime is not needed, because we do not need to think in human clock terms (hours, minutes, seconds).

All we need is a number of seconds since any fixed moment in the past and time.monotonic does exactly that.

import time

DELAY = 900  # in seconds

start = time.monotonic()
# computation here
end = time.monotonic()
duration = end - start
time.sleep(DELAY - duration)

Last three lines can be written as time.sleep(start + DELAY - time.monotonic()), I split it for simplicity.

VPfB
  • 14,927
  • 6
  • 41
  • 75
-2
import time
import random
import datetime

wait = random.randint(1, 14)

now = datetime.datetime.utcnow()
print(now)

time.sleep(wait * 60)

now = datetime.datetime.utcnow()
print(now)

I think this solves it.

random
  • 62
  • 1
  • 7