简体   繁体   中英

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

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 

It's because schedule does not account for the time it takes for the job function to execute . Use ischedule instead. The following would work for your task.

import ischedule

ischedule.schedule(geeks, interval=2*60)
ischedule.run_loop()

import time
from datetime import datetime
from simple_scheduler.recurring import recurring_scheduler
    
recurring_scheduler.add_job(target=geeks, period_in_seconds=5*60)
recurring_scheduler.run()

Too late to answer I guess. source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM