簡體   English   中英

如何讓程序睡到第二天

[英]How to make program sleep until next day

我需要我的代碼停止並等到第二天。 時間無關緊要,我只需要它在日期更改時繼續。

currentDate = datetime.datetime.now()

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

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

代碼暫停但之后不繼續

這里有兩個選項和評論。

先做進口

import datetime
import time
  • 一個使用 while 循環 - 可能不是一個好的解決方案,但強調了一種等待條件得到滿足的方法。
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)
  • 另一個 - 從現在到明天睡覺的秒數
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)

您可以為此目的使用 schedule,這將使您可以在需要時靈活地重構代碼,而無需編寫大量代碼。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM