Flask中使用定時任務

1. 安裝所需包

pip install SQLAlchemy
pip install flask_apscheduler

2. 定義定時任務配置類


from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore

from schedules.task import task1, task2


# 任務配置類
class SchedulerConfig(object):
    # 配置執行job
    JOBS = [
         {
            'id': 'put_into_queue',
            'func': task1,
            'args': None,
            'trigger': 'interval',
            'seconds': 60 * 3 # 本任務爲每3分鐘執行一次
        },
        {
            'id': 'scheduler_dev_queueing',
            'func': task2,
            'args': None,
           'trigger':{ # 本任務爲每週一五點五十九分四十秒執行一次
                'type': 'cron',  # 類型
                'day_of_week': "0", # 可定義具體哪幾天要執行
                'hour': '5',  # 小時數
                'minute': '59',
                'second': '40'  # "*/3" 表示每3秒執行一次,單獨一個"3" 表示每分鐘的3秒。現在就是每一分鐘的第3秒時循環執行。
            }
        }
    ]
    # 存儲位置
    SCHEDULER_JOBSTORES = {
        'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
    }
    # 線程池配置
    SCHEDULER_EXECUTORS = {
        'default': {'type': 'threadpool', 'max_workers': 20}
    }

    SCHEDULER_JOB_DEFAULTS = {
        'coalesce': False,
        'max_instances': 3
    }
    # 調度器開關
    SCHEDULER_API_ENABLED = True

3. 啓動時加載定時任務

if __name__ == '__main__':
    # 定時任務
    app.config.from_object(SchedulerConfig())
    scheduler = APScheduler()
    # 註冊app
    scheduler.init_app(app)
    scheduler.start()
    app.run(host="0.0.0.0", port=5001, use_reloader=False)

4. 定時任務中配置

1. cron定時調度

  • year (int|str) – 4位數年份
  • month (int|str) – 月(1-12)
  • day (int|str) – 日(1-31)
  • week (int|str) – ISO week (1-53)
  • day_of_week (int|str) – 工作日的編號或名稱(0-6或週一、週二、週三、週四、週五、週六、週日)使用名稱可能會報錯,建議使用數字
  • hour (int|str) – hour (0-23)
  • minute (int|str) – minute (0-59)
  • second (int|str) – second (0-59)
  • start_date (datetime|str) – 最早可能觸發的日期/時間(包括)
  • end_date (datetime|str) – 最晚可能觸發的日期/時間(包括)
  • timezone (datetime.tzinfo|str) – 用於日期/時間計算的時區(默認爲計劃程序時區)

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) – 間隔計算的起點
  • end_date (datetime|str) – 最晚可能觸發的日期/時間
  • timezone (datetime.tzinfo|str) – 用於日期/時間計算的時區

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

5. 注意事項

  1. 根據任務實際場景選擇合適的定時任務執行方式
  2. 啓動時最好設置use_reloader=False,這樣就取消了重新加載機制,防止定時任務重複執行.
  3. 本示例中使用sqlite3,需要的童鞋還可以使用mysql作爲定時任務存儲庫

6. 官方網址

flask-apscheduler擴展

apscheduler文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章