Python APScheduler介紹及使用

柠柠七發表於2024-03-20

在許多應用程式中,需要定期執行某些任務,例如傳送電子郵件、生成報告或清理臨時檔案等。為了管理和排程這些任務,Python中有許多優秀的排程器庫,其中APScheduler是一個流行且功能強大的選擇。本文將介紹APScheduler的基本概念,並展示如何使用它來實現定時任務排程。

一、APScheduler簡介

APScheduler是一個輕量級的Python任務排程庫,提供了多種排程器(Scheduler)、觸發器(Trigger)和作業儲存(Job Store)等元件,可以滿足各種定時任務排程需求。它的特點包括:

靈活的排程方式:支援間隔排程、定時排程、CRON表示式排程等多種排程方式。
多種觸發器:提供了簡單的時間觸發器、日期觸發器、CRON觸發器等多種觸發器型別。
可擴充套件的作業儲存:支援記憶體、資料庫等多種作業儲存方式,方便管理和持久化儲存作業資訊。

二、安裝APScheduler

在開始使用APScheduler之前,首先需要安裝該庫。

pip install apscheduler

三、使用示例

1 建立定時任務
下面是一個簡單的示例,演示瞭如何使用APScheduler建立一個每隔5秒執行一次的定時任務。

"""
interval引數說明
    weeks               (int)                   number of weeks to wait
    days                (int)                   number of days to wait
    hours               (int)                   number of hours to wait
    minutes             (int)                   number of minutes to wait
    seconds             (int)                   number of seconds to wait
    start_date          (datetime|str)          starting point for the interval calculation
    end_date            (datetime|str)          latest possible date/time to trigger on
    timezone            (datetime.tzinfo|str)   time zone to use for the date/time calculations
    --------------------------------------------------------------------------------
    weeks               (int)                   間隔幾周
    days                (int)                   間隔幾天
    hours               (int)                   間隔幾小時
    minutes             (int)                   間隔幾分鐘
    seconds             (int)                   間隔多少秒
    start_date          (datetime 或 str)        開始日期
    end_date            (datetime 或 str)        結束日期
    timezone            (datetime.tzinfo 或str)  用於日期/時間計算的時區
"""
from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler

# 定義任務函式
def job_function():
    print("Hello World")

# 建立排程器
sched = BlockingScheduler()

# 安排每兩小時呼叫一次
sched.add_job(job_function, 'interval', hours=2)
# 與之前相同,但於2010年10月10日9:30開始,於2014年6月15日11:00停止
sched.add_job(job_function, 'interval', hours=2, start_date='2010-10-10 09:30:00', end_date='2014-06-15 11:00:00')

# 啟動排程器
sched.start()

2 使用CRON表示式
除了間隔排程外,APScheduler還支援使用CRON表示式來指定定時排程。

"""
cron引數說明
    year            (int|str) – 4-digit year
    month           (int|str) – month (1-12)
    day             (int|str) – day of the (1-31)
    week            (int|str) – ISO week (1-53)
    day_of_week     (int|str) – number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)
    hour            (int|str) – hour (0-23)
    minute          (int|str) – minute (0-59)
    second          (int|str) – second (0-59)
    start_date      (datetime|str) – earliest possible date/time to trigger on (inclusive)
    end_date        (datetime|str) – latest possible date/time to trigger on (inclusive)
    timezone        (datetime.tzinfo|str) – time zone to use for the date/time calculations (defaults to scheduler timezone)
"""
from apscheduler.schedulers.blocking import BlockingScheduler

def job_function():
    print("Hello World")

# 建立排程器
sched = BlockingScheduler()

# 6月、7月、8月、11月和12月的00:00、01:00、02:00和03:00
sched.add_job(job_function, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3')
# 週一至週五上午5:30執行至2014-05-30 00:00:00
sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30, end_date='2014-05-30')
# 每天凌晨1點執行任務
scheduler.add_job(job_function, 'cron', hour=1, minute=0)

# 啟動排程器
sched.start()

3 新增任務監聽器
可以新增任務監聽器來監聽任務的執行狀態,例如任務開始、任務執行出錯等。

def my_listener(event):
    if event.exception:
        print('任務出錯了!')

scheduler.add_listener(my_listener, 'job_error')

四、高階用法

1 新增持久化儲存
可以將任務排程資訊儲存到持久化儲存中,以便在應用重啟後恢復排程狀態。

from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore

jobstores = {
    'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
scheduler = BlockingScheduler(jobstores=jobstores)

結語

透過本文的介紹,您已經瞭解了APScheduler的基本概念及如何使用它來實現定時任務排程。APScheduler提供了豐富的排程方式和靈活的配置選項,能夠滿足各種複雜的任務排程需求。在實際應用中,可以根據具體情況選擇合適的排程方式和配置選項,並根據需要新增任務監聽器和持久化儲存,以提高任務排程的可靠性和可維護性。

相關文章