【问题标题】:How to use Schedule module with a conditional while loop in Python如何在 Python 中使用带有条件 while 循环的 Schedule 模块
【发布时间】: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


    【解决方案1】:

    将条件语句移到printjob函数中,不要使用嵌套while循环(这里的代码在营业时间和非营业时间切换)。计划任务连续运行,但您的函数 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()
    

    【讨论】:

      猜你喜欢
      • 2014-12-22
      • 2014-04-30
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      相关资源
      最近更新 更多