Schedule python clear jobs queue

自古美人都是妖i 提交于 2021-01-29 15:17:41

问题


I’m a trying to use schedule as follows:

def job():
   my code

schedule.every().day.at("06:03").do(job)
schedule.every().day.at("09:56").do(job)

while True:
   schedule.run_pending()
   sleep(1)

My job can’t take from 1 to 10 hours to finish executing.

The problem that I’m having is this:

Basically, when the first job runs (at 06:03) if the job takes around 10 hours, right when it ends it starts again because schedule runs all the jobs that it has been missing (in this case it missed the job at 09:56, and therefore it runs that).

However what I want is that if the job takes very long the schedule that it has been missing doesn’t run right after, but it has to start again from the next schedule (in the example at 06:03). Simply put, if a schedule is missed, the “scheduler queue “ needs to be cleaned and start again from the next scheduled time. All the scheduled times missed don’t need to be ran.


回答1:


Here an example of a barebone solution for what you need, I try not to optimize to be clear.

It Is a job that just before the end reschedules itself and clears the existing instance.

import time
import schedule

def job_every_nsec(seconds=10):
    ### Job code
    print("before_job_every_nsec", time.time()) 
    time.sleep(20) 
    print("after_job_every_nsec", time.time())
    ### End of job code 
    # after the code of your job schedule the same job again
    # notice that the functions calls itself (recursion)
    schedule.every(seconds).seconds.do(job_every_nsec, seconds=seconds)
    # and clear the existing one
    return schedule.CancelJob

def job_at(start_at):
    ### Job code
    print("before job_at", time.time()) 
    time.sleep(20) 
    print("after job_at", time.time())
    ### End of job code 
    # after the code of your job schedule the same job again
    schedule.every().day.at(start_at)
    # and clear the existing one
    return schedule.CancelJob


# launch jobs for the first time
schedule.every(10).seconds.do(job_every_nsec, seconds=10)
schedule.every().day.at("12:30").do(job_at, start_at="12:30")

while True:
    schedule.run_pending()
    time.sleep(1)


来源:https://stackoverflow.com/questions/62259210/schedule-python-clear-jobs-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!