Replies: 4 comments 11 replies
-
@agronholm can you help me with this question? |
Beta Was this translation helpful? Give feedback.
-
Where are you starting the scheduler? What have you tried to expose the scheduler to the application? |
Beta Was this translation helpful? Give feedback.
-
This is how I have set this up is by adding it to the app.state inside the middleware. async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] == "lifespan":
async with self.scheduler:
await self.scheduler.start_in_background()
self.app.state.scheduler = self.scheduler # <- add scheduler to app state.
await self.app(scope, receive, send)
else:
await self.app(scope, receive, send) You can get the scheduler from the request state now. def get_scheduler_from_request(request: Request) -> AsyncScheduler:
return request.state.scheduler |
Beta Was this translation helpful? Give feedback.
-
Just a follow up for anyone needing this. To resolve this I have a simplified solution that is very clean. main.py from apscheduler import AsyncScheduler
from fastapi import FastAPI
from fastapi.concurrency import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
# Lifespan startup actions
scheduler = AsyncScheduler()
async with scheduler:
await scheduler.start_in_background()
app.state.scheduler = scheduler
yield # Lifespan yeilds to the main app
# Lifespan shutdown actions
app = FastAPI(lifespan=lifespan) depend_scheduler.py from apscheduler import AsyncScheduler
from fastapi import Request
def get_scheduler(request: Request) -> AsyncScheduler:
return request.app.state.scheduler Then in a route you can inject the dependance. from typing import Annotated
from apscheduler import AsyncScheduler
from fastapi import APIRouter, Depends
from depend_scheduler import get_scheduler
router = APIRouter()
@router.post("/scheduler/")
async def get_scheduler(
scheduler: Annotated[AsyncScheduler, Depends(get_scheduler)],
):
jobs = await scheduler.get_jobs() |
Beta Was this translation helpful? Give feedback.
-
I want to add schedules from routes. How I can make this?
Beta Was this translation helpful? Give feedback.
All reactions