[英]Run job at specific 5 mins interval in python
I would like to run the job at:00, :05, :10, :15, :20, ....., :55.我想在: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因此,如果代码在16:31:10开始执行,则作业应该在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但工作在16:36:10运行
I got this result using python-cron module:我使用python-cron模块得到了这个结果:
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.可以使用
schedule
模块来实现结果。
First calculate the time until the 5 minute mark.首先计算到 5 分钟标记的时间。 Run a one off job that starts at that time, and use that job to trigger a job that runs every 5 minutes.
运行从那时开始的一次性作业,并使用该作业触发每 5 分钟运行一次的作业。
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.这大致给出了预期的结果,尽管时间似乎比 5 分钟大关漂移了几秒钟。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.