Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for lifespan tasks #3312

Merged
merged 13 commits into from
May 22, 2024
Merged

add support for lifespan tasks #3312

merged 13 commits into from
May 22, 2024

Conversation

Lendemor
Copy link
Collaborator

@Lendemor Lendemor commented May 16, 2024

Add support for running task during the whole lifespan of the app, rather than linked to any specific state.

import asyncio
import reflex as rx

@rx.page()
def index():
    return rx.box(), rx.color_mode.button(position="top-right")

async def long_running_task(key: str = "A"):
    i = 1
    while True:
        await asyncio.sleep(5)
        print(f"{key}: Oh I woke up {i} times.... Back to sleep again")
        i += 1


async def longer_running_task():
    while True:
        await asyncio.sleep(10)
        print("I sleep more than the others.")

@contextlib.asynccontextmanager
async def my_custom_context():
    print("Startup process....")
    yield
    print("Shutdown process....")

app = rx.App()
app.register_lifespan_task(long_running_task)
app.register_lifespan_task(long_running_task, "B")
app.register_lifespan_task(longer_running_task)
app.register_lifespan_task(my_custom_context)

Copy link
Collaborator

@masenf masenf left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tasks should have a chance to clean up nicely without being cancelled right?

@Lendemor
Copy link
Collaborator Author

The tasks should have a chance to clean up nicely without being cancelled right?

I think it's up to the task itself to handle being cancelled cleanly, by using try/finally or catching the asyncio.CancelledError

Copy link
Collaborator

@masenf masenf left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good.

I'd like to see at least one test in the integration tests that exercises this.

Maybe have a lifespan task and lifespan contextmanager set a module global and send it to the frontend via an rx.var

reflex/app.py Show resolved Hide resolved
@masenf masenf merged commit 956a526 into main May 22, 2024
47 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants