mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2025-08-26 16:40:40 +03:00
add scheduler middleware
This commit is contained in:
parent
171a8019f7
commit
a63c3e2a43
@ -77,5 +77,5 @@ app.add_middleware(SchedulerMiddleware, scheduler=_scheduler_himself)
|
||||
|
||||
|
||||
# TODO: every not GET meth should reset cache
|
||||
# TODO: every scheduler task which needs to act on database hsould have access to connection pool via request
|
||||
# TODO: every scheduler task which needs to act on database should have access to connection pool via request - maybe ?
|
||||
# TODO: https://stackoverflow.com/questions/16053364/make-sure-only-one-worker-launches-the-apscheduler-event-in-a-pyramid-web-app-ru
|
||||
|
@ -1,23 +1,26 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import text
|
||||
from starlette.types import ASGIApp, Receive, Scope, Send
|
||||
|
||||
from apscheduler import AsyncScheduler
|
||||
from apscheduler.triggers.interval import IntervalTrigger
|
||||
|
||||
from app.database import AsyncSessionFactory
|
||||
from app.utils.logging import AppLogger
|
||||
|
||||
logger = AppLogger().get_logger()
|
||||
|
||||
|
||||
def tick():
|
||||
|
||||
logger.info(f">>>> Be or not to be...{datetime.now()}")
|
||||
async def tick():
|
||||
async with AsyncSessionFactory() as session:
|
||||
stmt = text("select 1;")
|
||||
logger.info(f">>>> Be or not to be...{datetime.now()}")
|
||||
result = await session.execute(stmt)
|
||||
logger.info(f">>>> Result: {result.scalar()}")
|
||||
return True
|
||||
|
||||
|
||||
class SchedulerMiddleware:
|
||||
# TODO: need access to request to be able to get db conn pool
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
app: ASGIApp,
|
||||
@ -30,7 +33,7 @@ class SchedulerMiddleware:
|
||||
if scope["type"] == "lifespan":
|
||||
async with self.scheduler:
|
||||
await self.scheduler.add_schedule(
|
||||
tick, IntervalTrigger(seconds=25), id="tick"
|
||||
tick, IntervalTrigger(seconds=25), id="tick-sql-25"
|
||||
)
|
||||
await self.scheduler.start_in_background()
|
||||
await self.app(scope, receive, send)
|
||||
|
Loading…
x
Reference in New Issue
Block a user