Skip to content

Commit 1607598

Browse files
committed
examples: add background thread to refresh bottom toolbar
Modified getting_started.py to spawn a background thread that triggers a UI redraw twice a second. This ensures that dynamic content in the bottom toolbar, such as the timestamp, stays current while waiting for user input.
1 parent 3833025 commit 1607598

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

examples/getting_started.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
"""
1717

1818
import pathlib
19+
import threading
20+
import time
1921

2022
from rich.style import Style
2123

@@ -48,6 +50,12 @@ def __init__(self) -> None:
4850
startup_script=str(alias_script),
4951
)
5052

53+
# Spawn a background thread to refresh the bottom toolbar twice a second.
54+
# This is necessary because the toolbar contains a timestamp that we want to keep current.
55+
self._stop_refresh = False
56+
self._refresh_thread = threading.Thread(target=self._refresh_bottom_toolbar, daemon=True)
57+
self._refresh_thread.start()
58+
5159
# Prints an intro banner once upon application startup
5260
self.intro = (
5361
stylize(
@@ -84,6 +92,20 @@ def __init__(self) -> None:
8492
)
8593
)
8694

95+
def _refresh_bottom_toolbar(self) -> None:
96+
"""Background thread target to refresh the bottom toolbar."""
97+
import contextlib
98+
99+
from prompt_toolkit.application.current import get_app
100+
101+
while not self._stop_refresh:
102+
with contextlib.suppress(Exception):
103+
# get_app() will return the currently running prompt-toolkit application
104+
app = get_app()
105+
if app:
106+
app.invalidate()
107+
time.sleep(0.5)
108+
87109
@cmd2.with_category(CUSTOM_CATEGORY)
88110
def do_intro(self, _: cmd2.Statement) -> None:
89111
"""Display the intro banner."""

0 commit comments

Comments
 (0)