簡體   English   中英

在 python 中以特定的 5 分鍾間隔運行作業

[英]Run job at specific 5 mins interval in python

我想在:00、:05、:10、:15、:20、.....、:55 運行工作。

因此,如果代碼在16:31:10開始執行,則作業應該在16:35:00運行

我正在使用以下代碼:

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)

但工作在16:36:10運行

在此處輸入圖像描述

我使用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()

在我的情況下,結果如下所示:

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

可以使用schedule模塊來實現結果。

首先計算到 5 分鍾標記的時間。 運行從那時開始的一次性作業,並使用該作業觸發每 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)

這大致給出了預期的結果,盡管時間似乎比 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM