flask-apscheduler控制定时任务

下载依赖

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)
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值