APScheduler (重點)


定時校正

  • 需求: mysql和redis兩個系統, mysql增加數據成功, redis未必添加成功, 這樣兩個系統的數據可能出現偏差, 所以需要定期對mysql和redis的數據進行同步
  • 解決方案: 每天執行一次定時任務, 讓mysql數據和redis數據進行同步

  • crontab

    • 是linux系統一個內置命令, 依賴於linux系統, 無動態管理任務(取消/暫停/修改任務配置)
    • 使用場景: 適合於普通的靜態任務
  • apscheduler

    • 獨立的定時器程序, 可以方便的管理定時任務
    • 使用場景: 需要動態生成/管理任務, 如下單后30分鍾可有效期
    • 安裝 pip install apscheduler
    • 支持三種觸發器
      • date 只執行一次
      • interval 周期執行 參數 時間間隔
      • cron 周期執行 參數 時間

調度器 Scheduler

負責管理定時任務

BlockingScheduler: 作為獨立進程時使用

  from apscheduler.schedulers.blocking import BlockingScheduler

  scheduler = BlockingScheduler()
  scheduler.start()  # 此處程序會發生阻塞

BackgroundScheduler: 在框架程序(如Django、Flask)中使用

  from apscheduler.schedulers.background import BackgroundScheduler

  scheduler = BackgroundScheduler()
  scheduler.start()  # 此處程序不會發生阻塞

執行器 executors

在定時任務該執行時,以進程或線程方式執行任務

ThreadPoolExecutor

  from apscheduler.executors.pool import ThreadPoolExecutor
  ThreadPoolExecutor(max_workers)  
  ThreadPoolExecutor(20) # 最多20個線程同時執行

使用方法

  executors = {
      'default': ThreadPoolExecutor(20)
  }
  scheduler = BackgroundScheduler(executors=executors)

ProcessPoolExecutor

  from apscheduler.executors.pool import ProcessPoolExecutor
  ProcessPoolExecutor(max_workers)
  ProcessPoolExecutor(5) # 最多5個進程同時執行

使用方法

  executors = {
      'default': ProcessPoolExecutor(3)
  }
  scheduler = BackgroundScheduler(executors=executors)

觸發器 Trigger

指定定時任務執行的時機

1) date 在特定的時間日期執行

from datetime import date

# 在2019年11月6日00:00:00執行
sched.add_job(my_job, 'date', run_date=date(2009, 11, 6))

# 在2019年11月6日16:30:05
sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5))
sched.add_job(my_job, 'date', run_date='2009-11-06 16:30:05')

# 立即執行
sched.add_job(my_job, 'date')  
sched.start()

2) 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

from datetime import datetime

# 每兩小時執行一次
sched.add_job(job_function, 'interval', hours=2)

# 在2010年10月10日09:30:00 到2014年6月15日的時間內,每兩小時執行一次
sched.add_job(job_function, 'interval', hours=2, start_date='2010-10-10 09:30:00', end_date='2014-06-15 11:00:00')

3) 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)

# 在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')

# 在2014年5月30日前的周一到周五的5:30執行
sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30, end_date='2014-05-30')

任務管理

方式1

job = scheduler.add_job(myfunc, 'interval', minutes=2)  # 添加任務
job.remove()  # 刪除任務
job.pause() # 暫定任務
job.resume()  # 恢復任務

方式2

scheduler.add_job(myfunc, 'interval', minutes=2, id='my_job_id')  # 添加任務    
scheduler.remove_job('my_job_id')  # 刪除任務
scheduler.pause_job('my_job_id')  # 暫定任務
scheduler.resume_job('my_job_id')  # 恢復任務

調整任務調度周期

job.modify(max_instances=6, name='Alternate name')

scheduler.reschedule_job('my_job_id', trigger='cron', minute='*/5')

停止APScheduler運行

scheduler.shutdown()

代碼

import time

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor

# 創建執行器  用於支持多進程/多線程
executor = ThreadPoolExecutor(max_workers=5)

# 創建調度器
scheduler = BackgroundScheduler(executors={'default': executor})


def func1(name, age):
    print(name, age)


# 添加任務
# date  只執行一次
# scheduler.add_job(func1, "date", run_date='2019-08-29 14:53:40', args=['zs', 30])
# interval 周期執行 參數是時間間隔
# scheduler.add_job(func1, "interval", seconds=10, args=['zs', 30])
# cron 周期執行 參數是時間   每月1號3點會執行一次
# scheduler.add_job(func1, "cron", day=1, hour=3, args=['zs', 30])

# 秒針每次到30時執行一次
scheduler.add_job(func1, "cron", second=30, args=['zs', 30])

# 啟動調度器
scheduler.start()

while True:
    time.sleep(24 * 60 * 60)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM