Technology Sharing

Flask uses scheduled tasks flask_apscheduler (APScheduler)

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Flask-APScheduler Description:

Flask-APScheduler is a Flask extension that adds support for APScheduler.

APScheduler has three built-in scheduling systems for you to use:

  • Cron-style scheduling (optional start/end time)

  • Interval-based execution (run job at even intervals, with optional start/end times)

  • One-time delayed execution (run a job once at a set date/time)

1. Install the flask_apscheduler library

pip install flask_apscheduler

2. Code in app.py

2.1 Initialize APScheduler

  1. # 创建Flask应用
  2. app = Flask(__name__)
  3. # 初始化APScheduler
  4. scheduler = APScheduler()

2.2 Usage

Describe the use of cron expressions here

Cron expression generator address:https://cron.ciding.cc/

Method 1: Use hard-coded method

  1. # 创建Flask应用
  2. app = Flask(__name__)
  3. # 初始化APScheduler
  4. scheduler = APScheduler()
  5. # 方式一硬编码;
  6. # 这些代码也可以放在if __name__ == '__main__':内,与调试运行方式有关,
  7. # 1.flask服务方式运行不会走if __name__ == '__main__':内代码;
  8. # 2.以Python文件(app.py)方式运行会走if __name__ == '__main__':内代码;
  9. scheduler.add_job(func=MyService.my_job, id='my_job', trigger='cron', second='0/5')
  10. scheduler.init_app(app=app)
  11. scheduler.start()

Method 2: Read configuration method

Configuration code

  1. class Config:
  2. JOBS = [
  3. {
  4. 'id': 'job1',
  5. 'func': 'app:MyService.my_job', # 注意这里的格式,app 是 Flask 应用对象的名称(app.py),: 后面是任务函数名
  6. 'trigger': 'cron',
  7. # 'day_of_week': '0-6', # 每天执行
  8. # 'hour': 18, # 18 点执行
  9. # 'inute': 30, # 30 分执行
  10. # 'econd': 5 # 0 秒执行
  11. 'second': '0/5'
  12. }
  13. # ,
  14. # {
  15. # 'id': 'job2',
  16. # 'func': task2, # 也可以直接使用函数名
  17. # 'trigger': 'interval',
  18. # 'econds': 30 # 每隔 30 秒执行一次
  19. # }
  20. ]
  21. SCHEDULER_API_ENABLED = True
  1. # 创建Flask应用
  2. app = Flask(__name__)
  3. # 初始化APScheduler
  4. scheduler = APScheduler()
  5. # 方式一硬编码
  6. # scheduler.add_job(func=MyService.my_job, id='my_job', trigger='cron', second='0/5')
  7. # 方式二读取配置
  8. app.config.from_object(Config())
  9. scheduler.init_app(app=app)
  10. scheduler.start()

3. Code in my_service.py (MyService class)

  1. from datetime import datetime
  2. from flask import Flask
  3. class MyService:
  4. @classmethod
  5. def my_job(cls):
  6. print(f"my_job,当前时间{datetime.now()}")

4. Overall project structure

5. Operation effect

Specific code

https://gitee.com/jxzcode_admin/flask-project.git

References

https://blog.csdn.net/m0_48770520/article/details/130735727