1、簡介
APScheduler是一個 Python 定時任務框架,使用起來十分方便。提供了基于日期、固定時間間隔以及 crontab 類型的任務,并且可以持久化任務、并以 daemon 方式運行應用。
2、APScheduler四個組件
APScheduler 四個組件分別為:觸發器(trigger),作業存儲(job store),執行器(executor),調度器(scheduler)。
觸發器(trigger)
包含調度邏輯,每一個作業有它自己的觸發器,用于決定接下來哪一個作業會運行。除了他們自己初始配置意外,觸發器完全是無狀態的
APScheduler 有三種內建的 trigger:
- date: 特定的時間點觸發
- interval: 固定時間間隔觸發
- cron: 在特定時間周期性地觸發
作業存儲(job store)
存儲被調度的作業,默認的作業存儲是簡單地把作業保存在內存中,其他的作業存儲是將作業保存在數據庫中。一個作業的數據講在保存在持久化作業存儲時被序列化,并在加載時被反序列化。調度器不能分享同一個作業存儲。
APScheduler 默認使用 MemoryJobStore,可以修改使用 DB 存儲方案
執行器(executor)
處理作業的運行,他們通常通過在作業中提交制定的可調用對象到一個線程或者進城池來進行。當作業完成時,執行器將會通知調度器。
最常用的 executor 有兩種:
- ProcessPoolExecutor
- ThreadPoolExecutor
調度器(scheduler)
通常在應用中只有一個調度器,應用的開發者通常不會直接處理作業存儲、調度器和觸發器,相反,調度器提供了處理這些的合適的接口。配置作業存儲和執行器可以在調度器中完成,例如添加、修改和移除作業
2、安裝
$ pip install apscheduler
接下來我們看下簡單的幾個示例:
1
2
3
4
5
6
7
8
9
10
|
= = = = = = = = = = = = = = = interval: 固定時間間隔觸發 = = = = = = = = = = = = = = = from apscheduler.schedulers.blocking import BlockingScheduler from datetime import datetime def job(): print (datetime.now().strftime( "%Y-%m-%d %H:%M:%S" )) # 定義BlockingScheduler sched = BlockingScheduler() sched.add_job(job, 'interval' , seconds = 5 ) sched.start() |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
= = = = = = = = = = = = = = = cron: 特定時間周期性地觸發 = = = = = = = = = = = = = = = import time from apscheduler.schedulers.blocking import BlockingScheduler def job(text): t = time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime(time.time())) print ( '{} --- {}' . format (text, t)) scheduler = BlockingScheduler() # 在每天22點,每隔 1分鐘 運行一次 job 方法 scheduler.add_job(job, 'cron' , hour = 17 , minute = '*/1' , args = [ 'job1' ]) # 在每天22和23點的25分,運行一次 job 方法 scheduler.add_job(job, 'cron' , hour = '22-23' , minute = '25' , args = [ 'job2' ]) scheduler.start() |
通過裝飾器scheduled_job()添加方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import time from apscheduler.schedulers.blocking import BlockingScheduler scheduler = BlockingScheduler() @scheduler .scheduled_job( 'interval' , seconds = 5 ) def job1(): t = time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime(time.time())) print ( 'job1 --- {}' . format (t)) @scheduler .scheduled_job( 'cron' , second = '*/7' ) def job2(): t = time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime(time.time())) print ( 'job2 --- {}' . format (t)) scheduler.start() |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/hghua/p/13268007.html