Forum Archive

Stopwatch with new ui module, is there a better solution than `threading`?

dansherman

As part of a larger project using the awesome new ui module, I'd like to make a stopwatch. I have a label displaying the time, and a button to reset the counter. I'm using the threading module to update the time in the background while waiting for taps. It works, but it seems like there is probably a cleaner way to do things. Any suggestions?

import ui
from time import time,sleep,strftime,gmtime
import threading

t = time()

def reset_button(sender):
    '@type sender: ui.Button'
    global t
    t = time()

class update_time(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        while True:
            sleep(1)
            v['display_timer'].text = strftime('%H:%M:%S', gmtime(time()-t))


v = ui.load_view('ragnar')

background = update_time()
background.start()
v.present(orientations=['portrait'])
omz

You could use the ui.delay function for this.

dansherman

Thanks! It looks like @ui.in_background does the trick too.

import ui
from time import time,sleep,strftime,localtime,gmtime

t = time()

def reset_button(sender):
    '@type sender: ui.Button'
    global t
    t = time()

@ui.in_background
def update_time():
    while True:
        sleep(1)
        v['countdown_timer'].text = strftime('%H:%M:%S', gmtime(time()-t))


v = ui.load_view('ragnar')
update_time()
v.present(orientations=['portrait'])