Using Python schedule module at certain times, but first run tends to run multiple times

11 Views Asked by At

I am running a schedule set to execute a function every 5 seconds between start_time and end_time. However, the first instance it runs tends to run multiple times. Why is this, how is the timing handled? Sample code below

import schedule
import time
from datetime import datetime

def job():
    print(f'Hello world {time.ctime()}')

start_time = datetime.strptime("10:00", "%H:%M").time()
end_time = datetime.strptime("11:00", "%H:%M").time()

schedule.every(5).seconds.do(job)

while True:
    current_time = datetime.now().time().replace(microsecond=0)
    if start_time <= current_time < end_time:
        schedule.run_pending()
    else:
        print('outside working hours')
    time.sleep(1)

I have tried rounding the current time to nearest second. I expected the job to run only once for the first time - why is it running multiple times, what is happening with the timing?

0

There are 0 best solutions below