FastAPI集成APsecheduler的BackgroundScheduler+mongodb(精简)

项目架构:

FastAPI(folder)

>app(folder)

>core(folder)

>models(folder)

>routers(folder)

>utils(folder)

main.py(file)

1 utils文件夹下新建schedulers.py

from apscheduler.schedulers.background import BackgroundScheduler

from apscheduler.jobstores.mongodb import MongoDBJobStore

#特殊说明:此处显示指定DB,会在DB里创建数据库apscheduler_db

jobstores={

'default':MongoDBJobStore(

database='apscheduler_db',

collection='custom_jobs',

host='localhost',

port=27017

)

}

#特殊说明:replace_existing=True会覆盖同名的JOB,但不影响数据库中的,仅处理job_id相同的冲突

scheduler=BackgroundScheduler(jobstores=jobstores,replace_existing=True)

2 main.py中在lifespan上下文初始化和关闭scheduler

import uvicorn

from contextlib import asynccontextmanager

from app.utils.schedulers import jobstores

scheduler=None

#特殊说明:yield中可以监控到正常结束比如ctrl+c,异常结束不能执行yield后代码

@asynccontextmanager

async def lifespan(app:FastAPI):

jobstores['default'].remove_all_jobs()

from app.utils.schedulers import scheduler

yield

scheduler.remove_all_jobs()

scheduler.shutdown(wait=False)

app=FastAPI(lifespan=lifespan)

3 models文件夹新建scheduler.py文件配置基础参数类和默认值

from pydantic import BaseModel

class job_config(BaseModel):

job_id:str="default"

job_name:str="default"

trigger_type:str="interval"

trigger_kwargs:dict={}

seconds:int=30

pass

4 api文件夹下添加sechedulers.py配置添加创建job方法

from app.utils.schedulers import scheduler

from app.models.schedulers import job_config

from fastapi import APIRouter

from typing import Coroutine,Callable

from datetime import datetime

@router.get("create_job")

def create_job(jobconfig,func):

try:

if jobconfig is None:

jobconfig=job_config()

scheduler.add_job(

func,

trigger=jobconfig.trigger_type,

kwargs=jobconfig.trigger_kwargs,#特殊说明:这里可以添加自定义参数

id=jobconfig.job_id,

name=jobconfig.job_name,

seconds=jobconfig.seconds

)

scheduler.start()

except Exception as e:

raise e

except (KeyboardInterrupt, SystemExit):

scheduler.shutdown()

5 测试,调用test方法

@router.get("/function")

def function1():

try:

with open("D:\\demo.txt", "a") as file:

print("写入文件"+ str(datetime.now()), file=file)

except:

pass

@router.get("/test")

def test():

try:

create_job(None,function1)

except:

pass

相关推荐
曲幽10 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
曲幽1 天前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
曲幽3 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
曲幽4 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
闲云一鹤5 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
曲幽5 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
百锦再6 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
Li emily6 天前
解决了股票实时数据接口延迟问题
人工智能·fastapi
司徒轩宇7 天前
FastAPI + Uvicorn 深度理解与异步模型解析
fastapi