Skip to content

Commit 20e7ee5

Browse files
LineIndentAlek99
andauthored
fixes issue #1200 (#1256)
Co-authored-by: pourhakimi <[email protected]> Co-authored-by: Alek Petuskey <[email protected]>
1 parent b44be18 commit 20e7ee5

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

docs/events/background_events.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,34 @@ def background_task_example():
104104
)
105105
```
106106

107+
## Terminating Background Tasks on Page Close or Navigation
108+
109+
Sometimes, background tasks may continue running even after the user navigates away from the page or closes the browser tab. To handle such cases, you can check if the websocket associated with the state is disconnected and terminate the background task when necessary.
110+
111+
The solution involves checking if the client_token is still valid in the app.event_namespace.token_to_sid mapping. If the session is lost (e.g., the user navigates away or closes the page), the background task will stop.
112+
113+
```python
114+
import asyncio
115+
import reflex as rx
116+
117+
class State(rx.State):
118+
@rx.event(background=True)
119+
async def loop_function(self):
120+
while True:
121+
if self.router.session.client_token not in app.event_namespace.token_to_sid:
122+
print("WebSocket connection closed or user navigated away. Stopping background task.")
123+
break
124+
125+
print("Running background task...")
126+
await asyncio.sleep(2)
127+
128+
129+
@rx.page(on_load=State.loop_function)
130+
def index():
131+
return rx.text("Hello, this page will manage background tasks and stop them when the page is closed or navigated away.")
132+
133+
```
134+
107135
## Task Lifecycle
108136

109137
When a background task is triggered, it starts immediately, saving a reference to
@@ -118,6 +146,9 @@ the circumstances that are undesirable. In the example above, the `_n_tasks`
118146
backend var is used to control whether `my_task` will enter the increment loop,
119147
or exit early.
120148

149+
150+
151+
121152
## Background Task Limitations
122153

123154
Background tasks mostly work like normal `EventHandler` methods, with certain exceptions:

0 commit comments

Comments
 (0)