Coder Social home page Coder Social logo

Comments (3)

masenf avatar masenf commented on June 15, 2024 1

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.

NotAnyMike avatar NotAnyMike commented on June 15, 2024

Thank you for your answer, I will give it a try and get back to you!

from reflex.

NotAnyMike avatar NotAnyMike commented on June 15, 2024

Your idea worked great. thanks for suggesting it!

from reflex.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.