APScheduler with Rpyc & FastAPI attempting to achieve single instance #913
Unanswered
PREPONDERANCE
asked this question in
Q&A
Replies: 1 comment 6 replies
-
I tried using a file lock without rpyc and it worked fine with 4 workers but not desired when @asynccontextmanager
async def lifespan(app: FastAPI):
f = open("scheduler.lock", "wb")
global_scheduler = None
try:
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
scheduler_manager = SchedulerManager()
global_scheduler = scheduler_manager
scheduler_manager.start()
except Exception:
pass
yield
global_scheduler.shutdown()
fcntl.flock(f, fcntl.LOCK_UN)
f.close() |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Background info: I have a FastAPI project utilizing APScheduler for cron jobs. As the title suggests, since FastAPI will initialize multiple workers on start leading to multiple instances of APScheduler, I'm working on implementing a single-instance APScheduler.
After re-referencing to the FAQ and attempting to replicate the method provided by the author, I encounter some errors.
I create a
SchedulerManager
class encapsulating theSchedulerService
class that provides astart
API which is responsible for callingscheduler.start()
andserver.start()
. But when I add this to lifespan function and start my local server withuvicorn app.main:app --reload
(--reload
simply for test purposes), FastAPI simply stop reloading and cannot address any incoming requests. I suspect that when I start thisSchedulerManager
, it will somehow block the current event loop that FastAPI is running on.Then I tried start the FastAPI server with
uvicorn app.main:app --workers 4
to initialize multiple workers. This time it shows 'address already in use'.So why is this happening? Any workarounds to address this issue?
(I'm all aware 4.0 version will probably solve this issue for once and for all. But my current project require this feature very badly, so I need the solution desperately)
The code I mentioned is displayed below.
Beta Was this translation helpful? Give feedback.
All reactions