Use APScheduler in Flask to implement scheduled tasks

Scheduling scheduled tasks is a common feature in background applications. The APScheduler framework is a framework commonly used in Python to manage and schedule scheduled tasks. The framework is powerful and supports multiple scheduling methods. This article demonstrates how to integrate APSchedule in a Flask web application.

In this article, we use Flask-APScheduler to integrate APScheduler.

Introduction to the example

In this article, using a simple Flask example, assume that the project structure is as follows:

1
2
3
4
+ app
__init__.py
jobs.py
main.py

Flask applications are started by the app module, and specific scheduled tasks are written in the jobs.py file in the app module.

Install Flask-APScheduler

Execute:

1
pip install Flask-APScheduler

Define the scheduled task to perform

In the example, we simply define a method for printing one line of text

1
2
def job1():
print('job1 running....')

Define scheduling rules

In the init.py file of the app module, we initialize Flask and start APScheduler. By using the Config object, we define a scheduling rule that defines job1 execution at 6:50 a.m. from Monday to Friday.

Note: The func definition in JOBS must be written to correspond to import * from app.jobs, otherwise it is easy to get the module not found error

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from flask import Flask
from flask_apscheduler import APScheduler

from app.jobs import *

class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'app:job1',
'args': '',
'trigger': {
'type': 'cron',
'day_of_week':"mon-fri",
'hour':'6',
'minute':'50',
'second': '0'
}
}
]

app = Flask(__name__)

scheduler = APScheduler()
app.config.from_object(Config())
scheduler.init_app(app)
scheduler.start()

@app.route('/')
def index():
return 'hello'

本文标题:Use APScheduler in Flask to implement scheduled tasks

文章作者:Morning Star

发布时间:2022年01月06日 - 11:01

最后更新:2022年01月11日 - 18:01

原始链接:https://www.mls-tech.info/python/python-flask-apschedule-en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。