1. 程式人生 > 實用技巧 >flask框架開啟定時任務簡單案例flask_apscheduler

flask框架開啟定時任務簡單案例flask_apscheduler

#所需模組flask_apscheduler

#encodig=utf-8
from flask import Flask, request
from flask_apscheduler import APScheduler
 
 
class Config(object):  # 建立配置,用類
    # 任務列表
    JOBS = [  
        # {  # 第一個任務
        #     'id': 'job1',
        #     'func': '__main__:job_1',
        #     'args': (1, 2),
        #
'trigger': 'cron', # cron表示定時任務 # 'hour': 19, # 'minute': 27 # }, { # 第二個任務,每隔5S執行一次 'id': 'job2', 'func': '__main__:method_test', # 方法名 'args': (1,2), # 入參 'trigger': 'interval', # interval表示迴圈任務 '
seconds': 5, } ] def method_test(a,b): print(a+b) app = Flask(__name__) app.config.from_object(Config()) # 為例項化的flask引入配置 ## @app.route("/hello",methods=["POST","GET"]) def check(): return "success",200 if __name__ == '__main__': scheduler=APScheduler() scheduler.init_app(app) scheduler.start() app.run(debug
=False)

add_job的第二個引數是trigger,它管理著作業的排程方式。它可以為date, interval或者cron。對於不同的trigger,對應的引數也相同。

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) – 用於日期/時間計算的時區(預設為計劃程式時區)

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) – 用於日期/時間計算的時區

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