說明
安裝:
1 pip install apscheduler
首先來看一個週一到週五每天早上6點半喊我起牀的例子:
1 from apscheduler.schedulers.blocking import BlockingScheduler
2 from datetime import datetime
3 # 輸出時間
4 def job():
5 print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
6 # BlockingScheduler
7 scheduler = BlockingScheduler()
8 scheduler.add_job(job, 'cron', day_of_week='1-5', hour=6, minute=30)
9 scheduler.start()
APScheduler四個組件
觸發器(trigger)
- date: 特定的時間點觸發
- interval: 固定時間間隔觸發
- cron: 在特定時間週期性地觸發
作業存儲(job store)
執行器(executor)
- ProcessPoolExecutor
- ThreadPoolExecutor
調度器(scheduler)
配置調度器
1 from apscheduler.schedulers.blocking import BlockingScheduler
2 from datetime import datetime
3
4
5 def job():
6 print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
7 # 定義BlockingScheduler
8 sched = BlockingScheduler()
9 sched.add_job(job, 'interval', seconds=5)
10 sched.start()
1 from datetime import datetime
2 from pymongo import MongoClient
3 from apscheduler.schedulers.blocking import BlockingScheduler
4 from apscheduler.jobstores.memory import MemoryJobStore
5 from apscheduler.jobstores.mongodb import MongoDBJobStore
6 from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
7 # MongoDB 參數
8 host = '127.0.0.1'
9 port = 27017
10 client = MongoClient(host, port)
11 # 輸出時間
12 def job():
13 print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
14 # 存儲方式
15 jobstores = {
16 'mongo': MongoDBJobStore(collection='job', database='test', client=client),
17 'default': MemoryJobStore()
18 }
19 executors = {
20 'default': ThreadPoolExecutor(10),
21 'processpool': ProcessPoolExecutor(3)
22 }
23 job_defaults = {
24 'coalesce': False,
25 'max_instances': 3
26 }
27 scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
28 scheduler.add_job(job, 'interval', seconds=5, jobstore='mongo')
29 scheduler.start()
對 job 的操作
添加 job
-
add_job()
-
scheduled_job()
1 from apscheduler.schedulers.blocking import BlockingScheduler
2 sched = BlockingScheduler()
3 # 裝飾器
4 @sched.scheduled_job('interval', id='my_job_id', seconds=5)
5 def job_function():
6 print("Hello World")
7 # 開始
8 sched.start()
移除 job
-
remove_job()
-
job.remove()
1 job = scheduler.add_job(myfunc, 'interval', minutes=2)
2 job.remove()
3 # id
4 scheduler.add_job(myfunc, 'interval', minutes=2, id='my_job_id')
5 scheduler.remove_job('my_job_id')
暫停和恢復 job
1 apscheduler.job.Job.pause()
2 apscheduler.schedulers.base.BaseScheduler.pause_job()
恢復一個 job:
1 apscheduler.job.Job.resume()
2 apscheduler.schedulers.base.BaseScheduler.resume_job()
希望你還記得 apscheduler.job.Job 是 add_job() 返回的實例
獲取 job 列表
修改 job
1 job.modify(max_instances=6, name='Alternate name')
2 modify_job('my_job_id', trigger='cron', minute='*/5')
關閉 job
1 scheduler.shutdown()
2 scheduler.shutdown(wait=False)
scheduler 事件
1 def my_listener(event):
2 if event.exception:
3 print('The job crashed :(')
4 else:
5 print('The job worked :)')
6 # 添加監聽器
7 scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
trigger 規則
date
-
run_date (datetime|str) – the date/time to run the job at
-
timezone (datetime.tzinfo|str) – time zone for run_date if it doesn’t have one already
1 from datetime import date
2 from apscheduler.schedulers.blocking import BlockingScheduler
3 sched = BlockingScheduler()
4 def my_job(text):
5 print(text)
6 # The job will be executed on November 6th, 2009
7 sched.add_job(my_job, 'date', run_date=date(2009, 11, 6), args=['text'])
8 sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5), args=['text'])
9 sched.add_job(my_job, 'date', run_date='2009-11-06 16:30:05', args=['text'])
10 # The 'date' trigger and datetime.now() as run_date are implicit
11 sched.add_job(my_job, args=['text'])
12 sched.start()
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)
中文釋義:
參數
|
說明
|
(int|str)
|
表示參數既可以是int類型,也可以是str類型
|
(datetime | str)
|
表示參數既可以是datetime類型,也可以是str類型
|
year(int or str)
|
年,4位數字
|
month(int or str)
|
月(範圍1-12)
|
day(int or str)
|
日(範圍1-31)
|
week(int or str)
|
周(範圍1-53)
|
day_of_week(int or str)
|
周內第幾天或者星期幾(範圍0-6或者mon,tue,wed,thu,fri,stat,sun)
|
hour(int or str)
|
時(0-23)
|
minute(int or str)
|
分(0-59)
|
second(int or str)
|
秒(0-59)
|
start_date(datetime or str)
|
最早開始日期(含)
|
end_date(datetime or str)
|
最晚結束日期(含)
|
timezone(datetime.tzinfo or str) | 指定時區 |
表達式:
示例:
1 from apscheduler.schedulers.blocking import BlockingScheduler
2
3
4 def job_function():
5 print("Hello World")
6 # BlockingScheduler
7 sched = BlockingScheduler()
8 # Schedules job_function to be run on the third Friday
9 # of June, July, August, November and December at 00:00, 01:00, 02:00 and 03:00
10 sched.add_job(job_function, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3')
11 # Runs from Monday to Friday at 5:30 (am) until 2014-05-30 00:00:00
12 sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30, end_date='2014-05-30')
13 sched.start()
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
1 from datetime import datetime
2 from apscheduler.schedulers.blocking import BlockingScheduler
3
4
5 def job_function():
6 print("Hello World")
7 # BlockingScheduler
8 sched = BlockingScheduler()
9 # Schedule job_function to be called every two hours
10 sched.add_job(job_function, 'interval', hours=2)
11 # The same as before, but starts on 2010-10-10 at 9:30 and stops on 2014-06-15 at 11:00
12 sched.add_job(job_function, 'interval', hours=2, start_date='2010-10-10 09:30:00', end_date='2014-06-15 11:00:00')
13 sched.start()
踩坑記錄:
1、cron編寫場景爲每週五上午十點執行一次時,day_of_week字段爲4,即當前星期數-1,也可以寫成'fri'