Search code examples
pythonpython-3.xdatetimetimeminute

Dynamic time sleep until new minute starts with HH:MM:01 second


I have a python code which usually runs within 20 to 48 seconds.

Currently I am using time.sleep(10) after the code + with while true & Try to run the same code after 10 second.

My objective is to use time.sleep(dynamic) so that multiple iteration of my code in same time minute stamp(within same minute)can be stopped to remove duplication of data values.

For example :

##Let say Code runs at 12:30:01 pm

while True:
    try:
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")
        start = '11:45:01'
        end = '18:02:00'
        if current_time > start and current_time < end:while True:
            Import Code1  ## run first program file
            Import Code1  ## run second program file
            Time.sleep(3)
        else:
            print("out of time")
            time.sleep(3)
    except Exception as e:
        print(e)
        time.sleep(3)
        continue
    continue

Now if code finishes at 12:30:50 pm then time.sleep(remianing second) should be = 10. if code finishes at 12:30:57 pm then time.sleep(remianing second) should be = 3. and if code finishes at 12:30:40 pm then time.sleep(remianing second) should be = 20. and so on…

Restart next iteration at 12:31:01 second (or after).


Solution

  • You can sleep the necessary amount of remaining time up to a minute by marking the time when the work starts and finishes, e.g.

    import time
    import random
    
    
    while True:
        start_time = time.time()
        time.sleep(random.randint(2,5))  # do some work
        worked_time = time.time() - start_time
        print("worked for", worked_time)
        wait_to_align = 60.0 - worked_time % 60.0
        print(f"sleep {wait_to_align} to align to a minute")
        time.sleep(wait_to_align)
    

    produces

    worked for 3.002328634262085
    sleep 56.997671365737915 to align to a minute
    worked for 5.003056764602661
    sleep 54.99694323539734 to align to a minute
    ...