Search code examples
python-3.xtimeschedule

How to schedule function to run at fix point of time?


Is there any python library that can schedule a function(task) at fix point of time?

For example:

Every 5 mins: runs at xx:00, xx:05, xx:10 ...

Every 30 mins: runs at xx:00, xx:30 ...

Every 1 hours: runs at 00:00, 01:00, 02:00 ...

If I have to implement myself, is there any convenient utils that can calculates how many seconds I have to sleep before the time point?


Solution

  • Python have the library called schedule which helps to schedule the job or function at scheduled time.

    install using

    pip install schedule

    here is jupyter notebook python script which will demonstrate the example of schedule

    import schedule
    import time
    
    def job():
        print('I am working as scheduler....!')
    
    def lunch_job():
        print("Take lunch break, time is : 2.30 PM")
    
    def screen_break_job():
        print("Please take a small break, its been an hour seated")
    
    
    schedule.every(1).minutes.do(job)
    schedule.every().hour.do(screen_break_job)
    schedule.every().day.at("14:30").do(lunch_job)
    schedule.every().monday.do(job)
    schedule.every().wednesday.at("13:15").do(job)
    schedule.every().minute.at(":17").do(job)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    For more details, refer schedule