我需要每 5 分鐘運行一次特定的函式,從周日晚上 11 點開始到周五晚上 11 點。我該怎么做?我嘗試使用“計劃”模塊,在列印即時時間的一般功能下方
import time
from datetime import datetime
def script_sample():
now = datetime.now()
print(now)
schedule.every(5).minutes.sunday.at("23:00").until.friday.at("23:00").do(script_sample)
while True:
schedule.run_pending()
但我收到以下錯誤:
AttributeError: 'function' object has no attribute 'friday'
我該怎么做?“計劃”是這個任務的正確模塊嗎?
uj5u.com熱心網友回復:
您不能在 schedule API 中直接將 until 條件設定為星期幾和時間,但可以將顯式 datetime、time 或 timedelta 物件設定為函式中的引數until()。請參閱apidocs。
此外,您不能在一周中的某一天和每 x 分鐘安排一個作業。類似的東西schedule.every(5).minutes.sunday.at("23:00")是不允許的。
嘗試這樣的事情首先找到下周日的日期,然后從中計算下一個周五的日期。現在您有了開始和結束時間。
接下來,您可以呼叫 sleep 直到開始時間,然后您可以開始安排作業。
import time
from datetime import datetime, timedelta
import schedule
def script_sample():
now = datetime.now()
print(now)
now = datetime.now()
# find date of next sunday
d = now
# weekday(): Monday is 0 and Sunday is 6
while d.weekday() != 6:
d = timedelta(days=1)
d = d.replace(hour=23, minute=00, second=0, microsecond=0)
print("now=", now)
print("next sunday", d) # start date
wait_time = d - now
wait_time_secs = wait_time.total_seconds()
if wait_time_secs > 0:
print("wait time is ", wait_time)
print("waiting to start...")
time.sleep(wait_time_secs)
else:
print("no need to wait. let's get started')
這部分代碼將在周日 23:00 或周日晚些時候完成,如果它是在周日 23:00 之后開始的。
下面代碼的第 2 部分是確定直到條件并安排作業運行。接下來找到下周五的日期,這是時間表中的直到條件。最后安排作業每 5 分鐘運行一次,直到星期五 23:00。
# next find date of next Friday (friday=5)
while d.weekday() != 5:
d = timedelta(days=1)
endtime = d.replace(hour=23, minute=00, second=0, microsecond=0)
print("end time", endtime)
# now schedule a job every 5 mins until the end time
schedule.every(5).minutes.until(endtime).do(script_sample)
while True:
schedule.run_pending()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/483927.html
下一篇:Python日期時間計算
