fastapi 定时任务

    # server:
    if 1:
        from fastapi import FastAPI
        from apscheduler.schedulers.background import BackgroundScheduler
        import time

        app = FastAPI()
        scheduler = BackgroundScheduler(timezone="Asia/Shanghai")
        is_running = False  # 任务锁:防止上一轮没跑完,下一轮又触发

        def run_sql_task():
            global is_running
            if is_running:
                print(f"[{time.ctime()}] 任务正在执行,跳过本次触发")
                return
            try:
                is_running = True
                print(f"===== 定时任务开始 {time.strftime('%Y-%m-%d %H:%M:%S')} =====")
                # ======================
                # 这里放你的业务代码:遍历sqlite,查询unit_data_his,去重处理
                # ======================
                print(f"===== 定时任务结束 {time.strftime('%Y-%m-%d %H:%M:%S')} =====")
            except Exception as e:
                print(f"任务异常:{e}")
            finally:
                is_running = False


        # cron配置:每小时的55分执行
        scheduler.add_job(
            run_sql_task,
            trigger="cron",
            minute='*',   # 每小时55分触发
            id="hour_55_sql_task",
            replace_existing=True
        )

        scheduler.start()
        print("APScheduler已启动,每小时55分执行任务")



        @app.get("/")
        def root():
            return {"msg": "服务正常,定时任务:每小时55分运行"}
        import uvicorn
        uvicorn.run(app, host="0.0.0.0", port=8000)

posted on 2026-09-15 16:45  张博的博客  阅读(9)  评论(0)    收藏  举报

导航