簡體   English   中英

schedule (Python lib) - 如何在多個特定分鍾內運行作業

[英]schedule (Python lib) - How to run a job in multiple certain minutes of hour

我正在使用調度庫來調度 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)方法,但它不跨越:00秒。

所以,我尋求一種慣用的,或者至少是一種簡潔的方式來使用這個庫來實現它。 有嗎?

一種方法是終止最后一個調度進程,並以新的時間開始新的調度進程。 為了下次指定,我實現了一個不太整潔的功能。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM