Package Products :: Package ZenUtils :: Module Timeout |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenUtils.Timeout

     1  ##############################################################################
     2  #
     3  # Copyright (C) Zenoss, Inc. 2008, all rights reserved.
     4  #
     5  # This content is made available according to terms specified in
     6  # License.zenoss under the directory where your Zenoss product is installed.
     7  #
     8  ##############################################################################
     9
    10
    11  from twisted.internet import reactor
    12  from twisted.internet import defer
    13
    14 -class TimeoutDeferred(defer.Deferred):
    15      """A deferred that fires errback if the result doesn't come
    16      back in the given time period"""
    17
    18      timer = None
    19
    20 -    def __init__(self, other, timeout):
    21          """Wrap the passed deferred and return a new deferred that
    22          will timeout
    23
    24          @type other: a Deferred
    25          @param other: the deferred to wrap
    26          @type timeout: floating point number
    27          @param timeout: time, in seconds, to wait before failing the deferred
    28          """
    29          defer.Deferred.__init__(self)
    30          self.timer = reactor.callLater(timeout, self._timeout)
    31          other.chainDeferred(self)
    32
    33 -    def _timeout(self):
    34          "The wrapped deferred was too slow: fire the errback"
    35          if not self.called:
    36              self.timer = None
    37              self.errback(defer.TimeoutError())
    38
    39 -    def _startRunCallbacks(self, result):
    40          "We have a result, fire callbacks or cancel the timer"
    41          if self.timer:
    42              self.timer.cancel()
    43              self.timer = None
    44          if not self.called:
    45              defer.Deferred._startRunCallbacks(self, result)
    46
    47 -def timeout(deferred, timeInSeconds):
    48      "Utility method to wrap a deferred to timeout in timeInSeconds"
    49      return TimeoutDeferred(deferred, timeInSeconds)
    50