timer.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 
00003 import time
00004 import threading
00005 
00006 class Timer:
00007 
00008     def __init__(self, period = 1.0):
00009         self.timer_lock = threading.Lock()
00010         self.total_time = 0.0
00011         self.time_remaining = 0.0
00012         self.callback = None
00013         self.start_time = 0.0
00014         self.timer = None
00015         self.period = period
00016 
00017     def start(self, total_time, callback):
00018         self.timer_lock.acquire()
00019         success = False
00020         if not self.timer:
00021             self.timer = threading.Timer(self.period, self.tick)
00022             self.start_time = time.time()
00023             self.total_time = total_time
00024             self.time_remaining = total_time
00025             self.callback = callback
00026             self.timer.start()
00027             success = True
00028         self.timer_lock.release()
00029         return success
00030 
00031     def tick(self):
00032         callback = None
00033         self.timer_lock.acquire()
00034         if self.timer: # check in case cancel timer has been called
00035             current_time = time.time() 
00036             self.time_remaining = \
00037                     self.total_time - (current_time - self.start_time)
00038             if self.time_remaining <= 0.0:
00039                 callback = self.callback
00040                 self.reset_vars()
00041             else:
00042                 self.timer = threading.Timer(self.period, self.tick)
00043                 self.timer.start()
00044         self.timer_lock.release()
00045         if callback:
00046             callback()
00047 
00048     def cancel(self):
00049         self.timer_lock.acquire()
00050         success = False
00051         if self.timer:
00052             self.timer.cancel()
00053             self.reset_vars()
00054             success = True
00055         self.timer_lock.release()
00056         return success
00057 
00058     def time(self):
00059         return round(self.time_remaining)
00060 
00061     def reset_vars(self):
00062         self.total_time = 0.0
00063         self.time_remaining = 0.0
00064         self.callback = None
00065         self.start_time = 0.0
00066         self.timer = None
00067 


bwi_tools
Author(s): Piyush Khandelwal
autogenerated on Thu Jun 6 2019 17:57:26