My toga app needs to run a task every X seconds.
I prefer a multi-platform solution where possible.
I asked an AI and its solution used an external dependency (“schedule”) + additional loop + threading:
<code>
def create_timer(self, interval, callback):
def run_callback():
schedule.every(interval).seconds.do(callback)
while True:
schedule.run_pending()
threading.Event().wait(interval)
timer_thread = threading.Thread(target=run_callback)
timer_thread.daemon = True # Ensure thread terminates with app
timer_thread.start()
return timer_thread
</code>
<code>
def create_timer(self, interval, callback):
def run_callback():
schedule.every(interval).seconds.do(callback)
while True:
schedule.run_pending()
threading.Event().wait(interval)
timer_thread = threading.Thread(target=run_callback)
timer_thread.daemon = True # Ensure thread terminates with app
timer_thread.start()
return timer_thread
</code>
def create_timer(self, interval, callback):
def run_callback():
schedule.every(interval).seconds.do(callback)
while True:
schedule.run_pending()
threading.Event().wait(interval)
timer_thread = threading.Thread(target=run_callback)
timer_thread.daemon = True # Ensure thread terminates with app
timer_thread.start()
return timer_thread
I rather avoid external modules and adding loops (for performance, minimize resource usage, and simplicity).
How to implment a timer / interval based on Toga’s own event loop?