1

I would like to run the job at :00, :05 , :10, :15, :20, ....., :55.

So, if the execution of code started at 16:31:10 the job should run at 16:35:00

Am using the below code:

import schedule
import time
from datetime import datetime, timezone, timedelta


print("Started Exec:- " + str(datetime.now()))

def job():
    print("Job:- " + str(datetime.now()))


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


while True:
    schedule.run_pending()
    time.sleep(1)

But the job ran at 16:36:10

enter image description here

selet
  • 31
  • 3
  • Does [this](https://stackoverflow.com/questions/64963033/python-schedule-not-running-as-scheduled) help? Or, maybe it's because you're using `while True` (the code runs every time as there are no conditions for it to run). See https://stackoverflow.com/questions/3754620/what-does-while-true-mean-in-python. While what is true? – The Amateur Coder Apr 23 '22 at 11:23

2 Answers2

0

I got this result using python-cron module:

from datetime import datetime
import pycron


@pycron.cron('*/5 * * * * 0')
async def test(dt: datetime):
    print(f"test cron job running at {dt}")

if __name__ == '__main__':
    print(f"Started at {datetime.now().strftime('%Y-%m-%d, %H:%M:%S')}")
    pycron.start()

In my case result looks like:

Started at 2022-09-08, 11:03:54
test cron job running at 2022-09-08 11:05:00.059370
test cron job running at 2022-09-08 11:10:00.891355
test cron job running at 2022-09-08 11:15:00.700347
Vyacheslav
  • 77
  • 10
0

It is possible to achieve the result using the schedule module.

First calculate the time until the 5 minute mark. Run a one off job that starts at that time, and use that job to trigger a job that runs every 5 minutes.

import schedule
import time
from datetime import datetime, timedelta


print("Started Exec:- " + str(datetime.now()))

def repeat_job():
    print("repeat_job:- " + str(datetime.now()))

def initial_job():
    print("initial_job:- " + str(datetime.now()))
    schedule.every(5).minutes.do(repeat_job)
    return schedule.CancelJob

# Round the current time to the next 5 minute mark.
tm = datetime.now()
tm -= timedelta(minutes=tm.minute % 5,
                             seconds=tm.second,
                             microseconds=tm.microsecond)
tm += timedelta(minutes=5)

schedule.every().day.at(tm.strftime("%H:%M")).do(initial_job)

while True:
    schedule.run_pending()
    time.sleep(1)

This gives roughly the desired result, although the time appears to drift beyond the 5 minute mark by a couple of seconds.

Started Exec:- 2022-09-08 16:13:13.010702
initial_job:- 2022-09-08 16:15:00.181704
repeat_job:- 2022-09-08 16:20:00.638851
repeat_job:- 2022-09-08 16:25:01.066414
repeat_job:- 2022-09-08 16:30:01.492325
repeat_job:- 2022-09-08 16:35:01.899328
repeat_job:- 2022-09-08 16:40:02.353182
repeat_job:- 2022-09-08 16:45:02.785273
KyleL
  • 855
  • 6
  • 24