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.