我想使用匯入日期時間在每天下午 22:00 運行以下命令。我正在嘗試使用 codeRan 布林值來觸發它,但我無法讓它作業。它總是錯誤的:
import datetime
timeNow = datetime.datetime.now() # 2022-10-31 10:23:10.461374
timeHour = timeNow.strftime("%H") # 22
timeFull = timeNow.strftime("%X") # 10:21:59
timeAMPM = timeNow.strftime("%p") # AM or PM
codeRan = False
if timeHour == "22" and codeRan == False:
print(timeHour " That is correct!")
codeRan = True
elif timeHour == "22":
print("Script already ran. Wait 24 hours")
else:
print("Not time yet, it's only " timeFull ". The script will run at 22:00" timeAMPM)
uj5u.com熱心網友回復:
如果您的腳本在晚上 10 點至晚上 11 點之間運行,您撰寫的代碼將運行代碼print(timeHour " That is correct!")并列印。但是,您的代碼中沒有包含回圈,因此您需要使用一些外部方法來頻繁呼叫腳本以檢查是否該運行您的其他腳本。在 linux 中,您可以使用它來安排它每五分鐘運行一次,但是如果您打算這樣做,您可以使用它來安排它在晚上 10 點運行。在windows中也可以使用TaskScheduler。22 That is correct! crontabcrontab
如果你想使用 python,你真的有我能想到的三個選項(實際上可能更多)。
- 使用 while 回圈(可能是最簡單但最不優雅的解決方案,因為代碼將 24/7 運行
while True:
{your example code here}
使用cron或TaskScheduler
使用
subprocess.callPython 執行 #2。甚至可以檢查sys.platform以確定您使用的是 Linux 還是 Windows。檢查時間,然后休眠直到運行代碼。同樣,這不是很好,因為這意味著該程序必須一直保持活力。
此外,雖然您的方法或比較timeNow.strftime("%H") == '22'確實有效,但您也可以使用time.hour == 22.
uj5u.com熱心網友回復:
我不知道您的腳本的要求,但如果您只是想解決提出的問題,那么缺少一個簡單的 while:
while not codeRan:
if timeHour == "22" and codeRan == False:
print(timeHour " That is correct!")
codeRan = True
elif timeHour == "22":
print("Script already ran. Wait 24 hours")
else:
print("Not time yet, it's only " timeFull ". The script will run at 22:00" timeAMPM)
為了防止在沒有最少等待的情況下進行檢查,您可以在每次迭代結束時插入睡眠:
while not codeRan:
if timeHour == "25" and codeRan == False:
print(timeHour " That is correct!")
codeRan = True
elif timeHour == "22":
print("Script already ran. Wait 24 hours")
else:
print("Not time yet, it's only " timeFull ". The script will run at 22:00" timeAMPM)
time.sleep(num_of_seconds)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/524897.html
上一篇:從日期陣列中獲取日期范圍
