FastAPI实现定时任务
import pytz from apscheduler.schedulers.asyncio import AsyncIOScheduler # other schedulers are available from fastapi import FastAPI from fastapi_sqlalchemy import db from app.models import User, UserCount app = FastAPI() app.add_middleware(DBSessionMiddleware, db_url="sqlite://") @app.on_event('startup') async def startup_event():
# 自动执行数据库迁移
from alembic.command import upgrade
from alembic.config import Config
alembic_cfg = Config("alembic.ini")
upgrade(alembic_cfg, 'head')
scheduler = AsyncIOScheduler(timezone=pytz.utc)
scheduler.start()
scheduler.add_job(count_users_task, "cron", hour=0) # runs every night at midnight
def count_users_task(): """Count the number of users in the database and save it into the user_counts table.""" # we are outside of a request context, therefore we cannot rely on ``DBSessionMiddleware`` # to create a database session for us. Instead, we can use the same ``db`` object and # use it as a context manager, like so: with db(): user_count = db.session.query(User).count() db.session.add(UserCount(user_count)) db.session.commit() # no longer able to access a database session once the db() context manager has ended return users
好记性不如烂笔头!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)