Timer.py 1.03 KB
Newer Older
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
from time import time

class Timer(object):
    UP = 0
    DOWN = 1

    def __init__(self, delay=0):
        self.delay = delay
        self.time = delay
        self.active = False
        self.direction = self.DOWN if delay else self.UP
        self.lastUpdate = 0
    
    def update(self):
        if not self.lastUpdate:
            self.stop()        
        now = time()
        delta = now - self.lastUpdate
        self.lastUpdate = now
        if self.direction == self.UP:
            self.time += delta
        if self.direction == self.DOWN:
            self.time -= delta
        if self.time < 0:
            self.time = 0
            self.stop()

    def clear(self):
        self.time = self.delay

    def getTime(self):
        return self.time

    def getTimeString(self):
        return "{:02.0f}:{:05.2f}".format(self.time//60, self.time%60)

    def setTime(self, time):
        self.time = time

    def start(self):
        self.active = True
        self.lastUpdate = time()

    def stop(self):
        self.active = False