1# Copyright 2013 The Chromium Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4"""WatchdogTimer timeout objects.""" 5 6import time 7 8 9class WatchdogTimer(object): 10 """A resetable timeout-based watchdog. 11 12 This object is threadsafe. 13 """ 14 15 def __init__(self, timeout): 16 """Initializes the watchdog. 17 18 Args: 19 timeout: The timeout in seconds. If timeout is None it will never timeout. 20 """ 21 self._start_time = time.time() 22 self._timeout = timeout 23 24 def Reset(self): 25 """Resets the timeout countdown.""" 26 self._start_time = time.time() 27 28 def GetElapsed(self): 29 """Returns the elapsed time of the watchdog.""" 30 return time.time() - self._start_time 31 32 def GetRemaining(self): 33 """Returns the remaining time of the watchdog.""" 34 if self._timeout: 35 return self._timeout - self.GetElapsed() 36 else: 37 return None 38 39 def GetTimeout(self): 40 """Returns the timout of the watchdog.""" 41 return self._timeout 42 43 def IsTimedOut(self): 44 """Whether the watchdog has timed out. 45 46 Returns: 47 True if the watchdog has timed out, False otherwise. 48 """ 49 remaining = self.GetRemaining() 50 return remaining is not None and remaining < 0 51