Reflex Cloud - Fast, secure & scalable hosting. One command to deploy.

Background Tasks

A background task is a special type of EventHandler that may run concurrently with other EventHandler functions. This enables long-running tasks to execute without blocking UI interactivity.

A background task is defined by decorating an async State method with @rx.event(background=True).

Whenever a background task needs to interact with the state, it must enter an async with self context block which refreshes the state and takes an exclusive lock to prevent other tasks or event handlers from modifying it concurrently. Because other EventHandler functions may modify state while the task is running, outside of the context block, Vars accessed by the background task may be stale. Attempting to modify the state from a background task outside of the context block will raise an ImmutableStateError exception.

In the following example, the my_task event handler is decorated with @rx.event(background=True) and increments the counter variable every half second, as long as certain conditions are met. While it is running, the UI remains interactive and continues to process events normally.

Background events are similar to simple Task Queues like Celery allowing asynchronous events.

0 /

Task Lifecycle

When a background task is triggered, it starts immediately, saving a reference to the task in app.background_tasks. When the task completes, it is removed from the set.

Multiple instances of the same background task may run concurrently, and the framework makes no attempt to avoid duplicate tasks from starting.

It is up to the developer to ensure that duplicate tasks are not created under the circumstances that are undesirable. In the example above, the _n_tasks backend var is used to control whether my_task will enter the increment loop, or exit early.

Background Task Limitations

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

  • Background tasks must be async functions.
  • Background tasks cannot modify the state outside of an async with self context block.
  • Background tasks may read the state outside of an async with self context block, but the value may be stale.
  • Background tasks may not be directly called from other event handlers or background tasks. Instead use yield or return to trigger the background task.