multithreading - python add time to a countdown already running -
multithreading - python add time to a countdown already running -
i want have app if click button add together x amount of time running countdown timer.
i'm guessing have utilize threads not sure how implement it..
here code have far:
def countdown_controller(add_time): end_it = false def timer(time_this): start = time.time() lastprinted = 0 finish = start + time_this while time.time() < finish: = int(time.time()) if != lastprinted: time_left = int(finish - now) print time_left lastprinted = if end_it == true: = finish time.sleep(0.1) # check if counter running otherwise add together time. try: time_left except nameerror: timer(add_time) else: if time_left == 0: timer(add_time) else: add_this = time_left end_it = true while != finish: time.sleep(0.1) timer(add_time + add_this)
obviously not work, because every time phone call countdown_controller(15)
fx, start counting downwards 15 seconds , if click button nil happens until timer ended.
help appreciated.
i there flaw in design of code, because screen output blocks downwards entire programme doing nil (time.sleep(0.1)
).
typically want to in these cases having main loop in programme cycles through various operations create programme run. guarantees sensible distribution of scheme resources between various tasks.
in specific case, have in main loop is:
check user input (has time been added?) update output of countdownexample implementation:
import time import curses # timer class class timer(): def __init__(self): self.target = time.time() + 5 def add_five(self): self.target += 5 def get_left(self): homecoming int(self.target-time.time()) # main programme t = timer() stdscr = curses.initscr() stdscr.nodelay(true) curses.noecho() # main loop done in curses, can implement # gui toolkit or other method wish. while true: left = t.get_left() if left <= 0: break stdscr.addstr(0, 0, 'seconds left: %s ' % str(left).zfill(3)) c = stdscr.getch() if c == ord('x') : t.add_five() # final operations start here stdscr.keypad(0) curses.echo() curses.endwin() print '\ntime up!\n'
the above programme increment counter of 5 seconds if press x
key (lowercase). of code boilerplate utilize curses
module, of course of study if utilize pygtk, pyside or other graphical toolkit, different.
edit: rule of thumb, in python want avoid threading much can, both because (but not always) slows downwards programs (see "global interpreter lock") , because makes software harder debug/maintain.
hth!
python multithreading timer countdown
Comments
Post a Comment