[英]How to use Schedule module with a conditional while loop in Python
我正在嘗試使用 Schedule 模塊在一周的特定日期和特定時間(基本上是工作時間)運行任務。 當條件為真時,while 循環將起作用,但一旦條件為假,它就不會再次運行以查看時間范圍是否仍然適用。 我必須重新啟動腳本才能使其工作。
我對 Python 和自學很陌生。 這是我第一次在這里發帖,所以如果我的格式不正確或沒有包含足夠的信息,請糾正我。 我嘗試搜索論壇來解決我遇到的這個特定問題,但還沒有找到答案; 我可能搜索錯了。 這可能是一個簡單的問題,但幾天來我一直在絞盡腦汁。 這是我試圖用於另一個腳本的一小段代碼測試部分。 其他人推薦了 Cron,但由於這是一個更大的腳本,我只需要它的一部分來運行任務而不是整個事情。
from datetime import datetime as dt
import schedule
import time
def weekdayJob(x, i=None):
week = dt.today().weekday()
if i is not None and week < 5 and dt.now().hour in range(9,17):
schedule.every(i).minutes.do(x)
def printJob():
timestamp = time.strftime("%Y%m%d-%H%M")
print(f"test {timestamp}\n")
weekdayJob(printJob, 5)
while True:
schedule.run_pending()
time.sleep(5)
我也試過
from datetime import datetime as dt
import schedule
import time
def weekdayJob(x, i=None):
week = dt.today().weekday()
if i is not None and week < 5 and dt.now().hour in range(9,17):
schedule.every(i).minutes.do(x)
def printJob():
timestamp = time.strftime("%Y%m%d-%H%M")
print(f"test {timestamp}\n")
x = 1
while x == 1:
weekdayJob(printJob, 1)
time.sleep(5)
while True:
schedule.run_pending()
time.sleep(5)
我認為將預定的作業放在 while 循環中會使其不斷檢查條件語句是否為真,但情況似乎並非如此。 我將如何做到這一點,以便此腳本不斷檢查 weekdayJob 是否在所需的時間范圍內,這樣我就不必重新啟動腳本。
將條件語句移到printjob函數中,不要使用嵌套while循環(這里的代碼在營業時間和非營業時間之間切換)。 schedule 任務連續運行,但您的函數 if 語句僅在您定義的工作時間內運行。 這里以 1 分鍾的間隔運行(測試奇數與偶數分鍾),您可以指定自己的營業時間:
import datetime as dt
import schedule, time
from datetime import datetime
def printJob():
week = dt.datetime.today().weekday()
timestamp = time.strftime("%Y%m%d-%H%M")
if week < 5 and datetime.now().minute % 2 ==0: # in range(9,17):
print(f"business hours test...EVEN minutes... {timestamp}\n")
# your business hours function here...
else:
print(f'go home...test... ODD minutes... {timestamp}\n')
schedule.every(1).minute.do(printJob)
while True:
schedule.run_pending()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.