Search code examples
pythonschedule

Python schedule not running as scheduled


I am using below code to excute a python script every 5 minutes but when it executes next time its not excecuting at excact time as before. example if i am executing it at exact 9:00:00 AM, next time it executes at 9:05:25 AM and next time 9:10:45 AM. as i run the python script every 5 minutes for long time its not able to record at exact time. import schedule import time from datetime import datetime

# Functions setup  
      
def geeks(): 
    print("Shaurya says Geeksforgeeks") 
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    print("Current Time =", current_time) 
# Task scheduling 
# After every 10mins geeks() is called.  
schedule.every(2).minutes.do(geeks) 
# Loop so that the scheduling task 
# keeps on running all time. 
while True: 
  
    # Checks whether a scheduled task  
    # is pending to run or not 
    schedule.run_pending() 
    time.sleep(1) 

Is there any easy fix for this so that the script runs exactly at 5 minutes next time. please don't suggest me to use crontab as I have tried crontabs ut not working for me. I am using python script in different os


Solution

  • your geeks function will cost time to execute,and schedule job start calculate 5min after geeks done,that's why long time its not able to record at exact time. if you want your function run at exact time,you can trying this:

    
    # After every 10mins geeks() is called.  
    #schedule.every(2).minutes.do(geeks) 
    for _ in range(0,60,5):
        schedule.every().hour.at(":"+str(_).zfill(2)).do(geeks)
    # Loop so that the scheduling task