reflex icon indicating copy to clipboard operation
reflex copied to clipboard

Make it easier to exit a background task when the socket disconnects

Open masenf opened this issue 10 months ago β€’ 3 comments

Describe the Features For some use cases, I want to have an infinite loop that runs while the page is active and connected. Currently this can be accomplished via

@rx.event(background=True)
async def my_infinite_task(self):
        from app.app import app

        task_sid = self.router.session.session_id

        while task_sid == (
            app._event_namespace.token_to_sid.get(self.router.session.client_token, None)
        ):
            # do stuff
            await asyncio.sleep(5)

        # do cleanup
  • What is the purpose of the feature?

I want to write that same thing as

@rx.event(background=True, cancel=rx.Cancel.ON_DISCONNECT)
async def my_infinite_task(self):
    try:
        while True:
            # do stuff
            await asyncio.sleep(5)
    except asyncio.CancelledError:
        # do cleanup

Additional context Although there are more event driven ways to accomplish this (like rx.moment), this method is probably the most familiar approach (and common in llm generated code)

masenf avatar Mar 27 '25 22:03 masenf

In case it matters, this would be useful also in non-background tasks. In my use case, I'm using reflex for generating a constantly growing report that doesn't require the reflex event loop.

BTW, thanks a lot for posting this issue and the workaround, masenf. I ran into this and would spend a lot more time dealing with it if it wasn't for you.

SheldonHolmgren avatar Apr 01 '25 13:04 SheldonHolmgren

Talking about background tasks, could this be a way to connect to mqtt broker from reflex and plot the data being collected in real time? I opened an issue [https://github.com/reflex-dev/reflex/issues/5061] over a week ago regarding this problem and my sample code but haven't gotten any response from anyone regarding a way to accomplish this.

musa-cypher avatar Apr 08 '25 18:04 musa-cypher