下载依赖
pip install flask-apscheduler
scheduler_settings.py配置定时任务
import os.path
from flask_apscheduler import APScheduler
from sqlalchemysql import *
from datetime import datetime, timedelta
from contextlib import suppress
import re
class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'scheduler_settings:file_manage', # 第一个test为函数所在py文件名
'args': (), # 函数不需要参数时,可以设置为空元组,也可以直接省略
'trigger': 'cron', # 使用cron触发器
'day': '*', # * 表示每一天
'hour': '0', # 0时
'minute': '0',
'second': '0'
}
]
SCHEDULER_API_ENABLED = True
def file_manage():
with app.app_context():
print("run cmd file_manage-----------")
current_time = datetime.now()
one_day_ago = current_time - timedelta(days=1)
file_list = File.query.filter(File.is_delete == 0).all()
for file in file_list:
if os.path.isfile(file.pwd_path):
# 提取文件时间中的年、月、日、时、分、秒
match = re.search(r'(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})', file.time)
if match:
year, month, day, hour, minute, second = map(int, match.groups())
file_time = datetime(year, month, day, hour, minute, second)
if file_time < one_day_ago:
try:
os.remove(file.pwd_path)
file.is_delete = 1
db.session.commit()
except Exception as e:
print(f"删除文件失败: {e}")
# 手动删除上下文
with suppress(Exception):
app.app_context().pop()
app.config.from_object(Config())
scheduler = APScheduler()
scheduler.init_app(app) # 将调度器对象与Flask应用程序实例(app)相关联
scheduler.start()
app.py
if __name__ == "__main__":
app.run(port=2020,host="0.0.0.0",debug=True)