Issue
I am trying to delay commands with a delta from the initial time of execution. In other words, I want a start time point that the rest of the commands are delayed in reference to that start time point. Example:
print("start")
# command that delays for a minute since the start
print("it's been a 1 min")
# command that delays for n minute since the start
print("it's been n min")
I am trying to switch from sleep()
, but haven't found something that fits what I need. Any assistance is appreciated.
Solution
import time
initial_time = int(time.time()) #frame of reference in seconds
def delta_sleep(s):
"""
Parameters:
s: seconds since elapsed to sleep until
"""
if int(time.time()) > initial_time + s:
# check if the delta time has already passed
return
else:
# find time needed to sleep to reach the specified param 's'
needed_sleep = (initial_time+s) - int(time.time())
time.sleep(needed_sleep)
# example
print("The program has started")
delta_sleep(5)
print("Five seconds have passed")
delta_sleep(8)
print("8 seconds have passed")
delta_sleep(1) # does not sleep at all
Answered By - Keegan M
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.