flask框架开启定时任务简单案例flask

xiaoxiao2025-08-03  32

#所需模块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 waitdays (int) – number of days to waithours (int) – number of hours to waitminutes (int) – number of minutes to waitseconds (int) – number of seconds to waitstart_date (datetime|str) – 间隔计算的起点end_date (datetime|str) – 最晚可能触发的日期/时间timezone (datetime.tzinfo|str) – 用于日期/时间计算的时区

 

date定时调度

最基本的一种调度,作业只会执行一次。它的参数如下:run_date (datetime|str) – the date/time to run the job attimezone (datetime.tzinfo|str) – time zone for run_date if it doesn’t have one already

转载请注明原文地址: https://www.6miu.com/read-5034232.html

最新回复(0)