【问题标题】:schedule (Python lib) - How to run a job in multiple certain minutes of hourschedule (Python lib) - 如何在多个特定的小时内运行作业
【发布时间】:2019-02-14 14:40:01
【问题描述】:

我正在使用schedule 库来调度 Python 脚本。

我想要实现的是在每个小时的顶部和底部运行的作业(即 ...10:00、10:30、11:00...)。

我尝试了以下方法:

  • 当我将它用作schedule.every(30).minutes.do(job)时,作业开始的时间取决于程序的启动时间(如果它在10:17运行,它将在10:47、11:17等运行。 ) 这不是我需要的。

  • 还提供了一个schedule.every().hour.at(":30").do(job) 方法,但它不跨越:00s。

所以,我寻求一种惯用的,或者至少是一种简洁的方式来使用这个库来实现它。有吗?

【问题讨论】:

    标签: python schedule


    【解决方案1】:

    一种方法是终止上一个计划进程并以新的时间开始一个新的进程。为了指定下一次,我实现了一个不太简洁的函数。

    import schedule
    
    # an arbitrary start time
    start = '11:30'
    
    
    def next_time(start):
        ''' This function gives the next time. eg '13:00'->'13:30', '24:30'->'01:00' '''
        comp = start.split(':')
        if '30' in comp[1]:
            comp[1] = '00'
            comp[0] = str(int(comp[0]) + 1)
        else:
            comp[1] = '30'
        if int(comp[0]) > 24:
            comp[0] = '01'
        return ':'.join(comp)
    
    
    def job(time_now):
        print("The job has been done!")
        # kill the previous schedule, specified with a tag
        schedule.clear('previous')
        # the new time is calculated by next_time function
        next_point = next_time(time_now)
        # return a new one with the new time for the scheduled job
        return schedule.every().day.at(next_point).do(job, next_point).tag('previous')
    
    
    # implementing the schedule for first time
    schedule.every().day.at(start).do(job, start).tag('previous')
    
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 1970-01-01
      • 2023-01-29
      • 1970-01-01
      • 2022-01-11
      相关资源
      最近更新 更多