Streamlit Autorefresh

Hey everyone!

I created a custom component that triggers Streamlit to rerun on a user-specified interval. I was running across a lot of Streamlit apps using infinite loops, and while we can allow it in a script, I think this custom component will alleviate a lot of the stress of running an infinite loop on a server.

Here’s a trivial example.

import streamlit as st
from streamlit_autorefresh import st_autorefresh

# Run the autorefresh about every 2000 milliseconds (2 seconds) and stop
# after it's been refreshed 100 times.
count = st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter")

# The function returns a counter for number of refreshes. This allows the
# ability to make special requests at different intervals based on the count
if count == 0:
    st.write("Count is zero")
elif count % 3 == 0 and count % 5 == 0:
    st.write("FizzBuzz")
elif count % 3 == 0:
    st.write("Fizz")
elif count % 5 == 0:
    st.write("Buzz")
else:
    st.write(f"Count: {count}")

Solving the Infinite Loop

Streamlit apps with an infinite loop, utilize the time library to delay between calls.

import time
import streamlit as st

def get_data():
    # Perform some request to get a dataframe
    df = client.get()
    return df
    
table = st.empty()

while True:
     # update every 5 mins
     table.dataframe(get_data())
     time.sleep(300)  

With autorefresh, that is no longer needed. The script will finish executing, and the server will happily wait for the next rerun request.

import streamlit as st
from streamlit_autorefresh import st_autorefresh

# update every 5 mins
st_autorefresh(interval=5 * 60 * 1000, key="dataframerefresh")

def get_data():
    # Perform some request to get a dataframe
    client.get()
    return df

st.dataframe(get_data())

There are a couple features (limiting number of reruns and returning the run recount). Let me know if you have any questions. It’s a simple component so feedback is appreciated.

8 Likes

Awesome :smiley: love the idea of delegating the timer to the frontend!

Could you add it to the Community Tracker page :slight_smile: ?

1 Like

I get following error: To use Custom Components in Streamlit, you need to install PyArrow. Unfortunately, PyArrow does not yet support Python 3.9.

Hi @Ruben_S ! When Python 3.9 was released, PyArrow (which facilitates a serialization of pandas dataframes) did not support it. We added this error to inform users of this. It seems to be addressed, and we have removed it for the next release. You can try out pip install streamlit-nightly if you want to keep working on Python 3.9, or you can try using Python 3.8 using a tool like pyenv

Hope that helps!