aboutsummaryrefslogtreecommitdiff
path: root/catapult/devil/devil/utils/watchdog_timer.py
blob: 2c8a2250c5f81a6e1c26f9436c9cea6dca01dbbc (plain)
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
46
47
48
49
50
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""WatchdogTimer timeout objects."""

import time


class WatchdogTimer(object):
  """A resetable timeout-based watchdog.

  This object is threadsafe.
  """

  def __init__(self, timeout):
    """Initializes the watchdog.

    Args:
      timeout: The timeout in seconds. If timeout is None it will never timeout.
    """
    self._start_time = time.time()
    self._timeout = timeout

  def Reset(self):
    """Resets the timeout countdown."""
    self._start_time = time.time()

  def GetElapsed(self):
    """Returns the elapsed time of the watchdog."""
    return time.time() - self._start_time

  def GetRemaining(self):
    """Returns the remaining time of the watchdog."""
    if self._timeout:
      return self._timeout - self.GetElapsed()
    else:
      return None

  def GetTimeout(self):
    """Returns the timout of the watchdog."""
    return self._timeout

  def IsTimedOut(self):
    """Whether the watchdog has timed out.

    Returns:
      True if the watchdog has timed out, False otherwise.
    """
    remaining = self.GetRemaining()
    return remaining is not None and remaining < 0