Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Timer remaining time

Tags:

python

timer

How do I calculate the remaining time from the Python Timer object.

timer = Timer(10, print, ("expiry"))
timer.start()
...

from here, how do I find out what is the remaining time before the timer expired?

like image 484
TX T Avatar asked Aug 24 '17 17:08

TX T


1 Answers

just set a value when you start the thread Timer

timer = Timer(10, print, ("expiry"))
....
start_time = time.time()
timer.start()
time.sleep(3)
....
print ("Running for : %s seconds"%(time.time()-start_time))

You could always make your own timer class

class MyTimer(threading._Timer):
    started_at = None
    def start(self):
        self.started_at = time.time()
        threading._Timer.start(self)
    def elapsed(self):
        return time.time() - self.started_at
    def remaining(self):
        return self.interval - self.elapsed()


timer = MyTimer(10, print, ("expiry"))
timer.start()

for i in range(5):
    time.sleep(1)
    print (timer.remaining())
like image 126
Joran Beasley Avatar answered Nov 15 '22 04:11

Joran Beasley