Comments (3)
You really do not want to block in a background task.
Because reflex is an async-based framework, any non-async functions that are long running will block the whole server from processing other requests, sending deltas, etc.
If you need to execute blocking code in reflex, then you can farm it out to a separate process or thread and monitor the result in the background task.
In your code example above, you'll notice that if you open a second tab and try to click the button it actually wont do anything while the first tab is crunching along.
For simple stuff, you can use await asyncio.get_event_loop().run_in_executor(my_func)
to run the function in a thread and await the result.
For heavier or CPU-bound tasks, then you can run with a process pool. Here's some example
from __future__ import annotations
import asyncio
import multiprocessing
import multiprocessing.pool
import time
import reflex as rx
_global_pool: multiprocessing.Pool | None = None
class State(rx.State):
var: str = "Not Started"
def _pool(self) -> multiprocessing.Pool:
global _global_pool
if _global_pool is None:
_global_pool = multiprocessing.Pool()
return _global_pool
@rx.background
async def slow_task(self):
start_time = time.time()
async_result = self._pool().apply_async(time.sleep, (60,))
async with self:
self.var = "Working..."
print("Dispatched task to process pool")
# wait for the task to complete
while not async_result.ready():
await asyncio.sleep(1)
print(f"elapsed time: {time.time() - start_time}")
print(f"result: {async_result.get()}")
async with self:
self.var = "Done!"
def index() -> rx.Component:
return rx.container(
rx.vstack(
rx.button("Run slow task", on_click=State.slow_task),
rx.text(f"Status: {State.var}"),
align="center",
),
)
app = rx.App()
app.add_page(index)
from reflex.
Thank you for your answer, I will give it a try and get back to you!
from reflex.
Your idea worked great. thanks for suggesting it!
from reflex.
Related Issues (20)
- [REF-3006] Inline code rendered in `rx.markdown` has extra trailing space
- [REF-3010] Cannot access rx.color (and others) without first accessing rx.Component
- [REF-3011] Hash in URL does not jump to anchor defined in markdown
- [REF-3013] pyi_generator should not operate on changed files outside of `reflex/components`
- Cannot render states with typing.ForwardRef HOT 3
- [REF-3014] Bug in serializing lists/dict of `rx.Base` HOT 11
- [REF-3016] Upload ID should allow characters HOT 1
- [REF-3078] Make .web folder configurable via env. HOT 2
- Default color mode (dark/light) should be the host system's current mode
- [REF-3056] Cannot set state_manager.lock_expiration easily
- Buttons stop working after a sequence HOT 3
- [REF-3079] State hangs after using back button after following a link.
- [REF-2592] Backend Vars in ComponentState are not independent
- Deploy error HOT 1
- [REF-3098] DeprecationWarning with blank template HOT 1
- Removing Rich
- rx.moment() with from_now and local options set doesn't respect local TZ
- [REF-3107] Dynamic domain in sitemap
- How to add a custom tooltip to Recharts components?
- NGROK error
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from reflex.