Spaces:
Sleeping
Sleeping
File size: 1,655 Bytes
480eede |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
import asyncio
import time
import streamlit as st
from typing import Callable, Optional
class AsyncTimer:
def __init__(self, duration: int, on_complete: Callable, placeholder: Optional[st.empty] = None):
"""
Initialize async timer
Args:
duration: Duration in seconds
on_complete: Callback function to run when timer completes
placeholder: Optional streamlit placeholder to display timer
"""
self.duration = duration
self.on_complete = on_complete
self.placeholder = placeholder or st.empty()
self.start_time = None
self.is_running = False
def format_time(self, seconds: int) -> str:
"""Format seconds into MM:SS"""
mm, ss = seconds//60, seconds%60
return f"{mm:02d}:{ss:02d}"
async def start(self):
"""Start the countdown timer"""
self.start_time = time.time()
self.is_running = True
while self.is_running:
elapsed = int(time.time() - self.start_time)
remaining = max(0, self.duration - elapsed)
# Update display
self.placeholder.metric(
"Time Remaining",
self.format_time(remaining)
)
# Check if timer completed
if remaining <= 0:
self.is_running = False
await self.on_complete()
break
await asyncio.sleep(0.1) # Small delay to prevent excessive updates
def stop(self):
"""Stop the timer"""
self.is_running = False
|