Home > database >  How to make program sleep until next day
How to make program sleep until next day

Time:12-02

I need my code to stop and wait until the next day. The time does not matter, I just need it to continue when the date changes.

currentDate = datetime.datetime.now()

future = datetime.datetime(currentDate.year, currentDate.month, 
    (currentDate.day   1))

time.sleep((future-currentDate).total_seconds())

The code pauses but does not continue after

CodePudding user response:

Two options here with comments.

First do imports

import datetime
import time
  • one uses a while loop - probably not a good solution but highlights one way to wait for a condition to be met.
def loop_until_tomorrow():
    """ Will use a while loop to iterate until tomorrow """

    #get current date
    currentDate = datetime.datetime.now().date()
    # loop attempts 
    times = 0 
    # this will loop infiniatly if condition is never met 
    while True:
        # increment by one each iteration
        times  = 1
        #get date now
        now = datetime.datetime.now().date()
        if currentDate != now:
            # return when condition met             
            print("\nDay has changed")
            return 
        else:            
            # print attempts and sleep here to avoid program hanging 
            print(f"Attempt: {times}".ljust(13)   " - Not tomorrow yet!", end="\r")
            time.sleep(5)
  • the other - sleeps for the amount of seconds from now till tomorrow
def sleep_until_tomorrow():

    """wait till tomorrow using time.sleep"""
    
    #get date now
    now = datetime.datetime.now()
    #get tomorrows date 
    tomorrow_date = now.date()   datetime.timedelta(days=1)
    #set to datetime
    tomorrow_datetime = datetime.datetime(year=tomorrow_date.year, month=tomorrow_date.month, day=tomorrow_date.day, hour=0, minute=0, second=0)
    #get seconds
    seconds_til_tomorrow = (tomorrow_datetime-now).total_seconds()
    #sleep
    time.sleep(seconds_til_tomorrow)

CodePudding user response:

You can use schedule for that purpose, which will give you the flexibility to refactore the code when needed without having to write a chunck of code.

from schedule import every, repeat, run_pending
import time

#just to give you the idea on how to implement the module. 
@repeat(every().day.at("7:15"))
def remind_me_its_a_new_day():
    print("Hey there it's a new day! ")

while True:
    run_pending()
    time.sleep(1)
  • Related