from flask import Flask
from flask_apscheduler import APScheduler
app = Flask(__name__)
# scheduler 注册到 app
scheduler = APScheduler() # 实例化APScheduler
scheduler.init_app(app) # 把任务列表放进flask
if __name__ == '__main__':
scheduler.start() # 启动任务列表
# 一、装饰器方式
@scheduler.scheduler.scheduled_job(trigger='interval', id='apscheduler', seconds=2)
def apscheduler():
# 这个是每2秒执行一次
# trigger='interval' 表示是一个循环任务,每隔多久执行一次
print("APScheduler start")
# 二、添加方式
def apscheduler_add(a, b):
print(a + b)
scheduler.add_job(func=apscheduler_add, id='apscheduler_add', args=(1, 2), trigger='cron', day_of_week='0-6', hour=18, minute=19, second=10, replace_existing=True)
# trigger='cron' 表示是一个定时任务;
app.run(debug=True)
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