第一步:安裝APScheduler
pip install apscheduler
第二步:配置APScheduler
# 匯入模組
from apscheduler.schedulers.background import BackgroundScheduler
# 自定義定時啟動的任務
def my_job():
print("Hello World")
# 建立排程器例項
scheduler = BackgroundScheduler()
# 新增任務,指定任務執行的方式
scheduler.add_job(my_job, 'interval', hours=1)
# 啟動排程器
scheduler.start()
add_job的詳細配置案例
1.每隔一定時間執行job —— interval
from apscheduler.schedulers.blocking import BlockingScheduler
def my_interval_job():
print("Running my interval job!")
scheduler = BlockingScheduler()
# 每隔2分鐘執行一次作業
scheduler.add_job(my_interval_job, 'interval', minutes=2, id='my_interval_job')
scheduler.start()
2.根據Cron時間表執行job —— interval
from apscheduler.schedulers.blocking import BlockingScheduler
def my_cron_job():
print("Running my cron job!")
scheduler = BlockingScheduler()
# 每天上午10:15執行作業
scheduler.add_job(my_cron_job, 'cron', hour=10, minute=15, id='my_cron_job')
scheduler.start()
3.限制同時執行的job數量 —— max_instances
from apscheduler.schedulers.blocking import BlockingScheduler
def my_job():
print("Running my job!")
scheduler = BlockingScheduler()
# 同時只允許有3個例項執行
scheduler.add_job(my_job, 'interval', seconds=5, max_instances=3, id='my_job_with_limited_instances')
scheduler.start()
案例:指定時間段內間隔固定時間執行job
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime
def my_complex_job():
print("Running my complex job!")
scheduler = BlockingScheduler()
scheduler.add_job(
my_complex_job,
'cron',
day_of_week='mon-fri', # 週一至週五
hour=10,
minute=15,
start_date='2024-06-01', # 開始日期
end_date='2024-12-31', # 結束日期
week='*/2', # 每隔2周
misfire_grace_time=3600, # 1小時的寬限期
coalesce=True, # 合併錯過的作業
max_instances=2, # 最多2個例項
id='my_complex_cron_job'
)
scheduler.start()
檢視job狀態資訊
# 獲取所有作業
jobs = scheduler.get_jobs()
job = scheduler.get_job('my_job_id') # 獲取指定job資訊
# 列印每個作業的狀態
for job in jobs:
print(f"Job ID: {job.id}")
print(f"Name: {job.name}")
print(f"Next Run Time: {job.next_run_time}")
print(f"Trigger: {job.trigger}")
print("-" * 20)
# 監聽job執行狀態
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
def my_listener(event):
if event.exception:
print(f"The job crashed : {event.job_id}")
else:
print(f"The job worked : {event.job_id}")
scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)