简体   繁体   中英

Run job at specific 5 mins interval in python

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

在此处输入图像描述

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

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

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