Search code examples
pythonscheduled-tasks

How to schedule job with a particular time as well as interval?


Using python's schedule module how can I start a job at particular time and thereon it should be scheduled at regular intervals.

Suppose I want to schedule a task every 4 hours starting from 09:00 am.

schedule.every(4).hours.at("09:00").do(task) # This doesn't work

How to achieve the above?


Solution

  • You can convert the inner schedule (every 4 hours) into a separate function which would be called by the main schedule (fixed time). The inner schedule function would be the one calling your job function.

    Example -

    import schedule
    import time
    
    def job():
        print "I am working" #your job function
    
    def schedule_every_four_hours():
        job() #for the first job to run
        schedule.every(4).hour.do(job)
        return schedule.CancelJob
    
    schedule.every().day.at("09:00").do(schedule_every_four_hours)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    If you would like to kill the schedule based on your requirement read more here. Check here.