【发布时间】:2020-01-07 20:00:00
【问题描述】:
我正在尝试使用计划模块在一周中的特定日期和特定时间(基本上是营业时间)运行任务。当条件为真时,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 是否在所需的时间范围内,因此我不必重新启动脚本。
【问题讨论】:
标签: python while-loop conditional-statements schedule