1 回答

TA貢獻1824條經驗 獲得超6個贊
schedule.run_pending()簡單地循環運行所有到期的作業。帶有睡眠的循環決定檢查作業的頻率,定義作業何時運行的最小粒度。
每秒輪詢一次是不禮貌的。除非 CPU 無論如何都是空閑的,否則每次輪詢都會中斷一些其他任務,刷新內存緩存并通常增加宇宙的熵。您可以通過更改睡眠來設置不同的粒度。在此示例中,作業每 10 分鐘檢查一次。所以它可能在 10:10 而不是 10:00 運行。這可能很好,而且您中斷系統的次數減少了 600 次。每小時輪詢一次對于您的任務也可能是合理的。
JOB_GRANULARITY_SECONDS = 60 * 10
while True:
schedule.run_pending()
time.sleep(JOB_GRANULARITY_SECONDS)
但是當工作之間有很大的差距時,為什么不直接計算出確切的睡覺時間呢?您可以獲得下一份工作的時間并睡那么多時間(也許有一個軟糖因素來處理微小的波動,例如時鐘的粒度和時間協議在一些額外時間中的折騰)。此示例具有 2 秒的捏造粒度。
while True:
schedule.run_pending()
next_run_delta = (schedule.next_run - datetime.datetime.now()).total_seconds()
if next_run_delta <= 0:
continue
time.sleep(next_run_delta + 2)
您還可以添加異常處理,以應對一切都崩潰的情況
while True:
try:
schedule.run_pending()
except Exception as e:
my_alert_fctn(f"Scheduler failed, {e}") # email maybe?
next_run_delta = (schedule.next_run - datetime.datetime.now()).total_seconds()
if next_run_delta < 0:
continue
time.sleep(next_run_delta + 2)
添加回答
舉報