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

# Source Code for Module Products.ZenUtils.Timeout

     1  ###########################################################################
     2  #
     3  # This program is part of Zenoss Core, an open source monitoring platform.
     4  # Copyright (C) 2008, Zenoss Inc.
     5  #
     6  # This program is free software; you can redistribute it and/or modify it
     7  # under the terms of the GNU General Public License version 2 or (at your
     8  # option) any later version as published by the Free Software Foundation.
     9  #
    10  # For complete information please visit: http://www.zenoss.com/oss/
    11  #
    12  ###########################################################################
    13  from twisted.internet import reactor
    14  from twisted.internet import defer
    15
    16 -class TimeoutDeferred(defer.Deferred):
    17      """A deferred that fires errback if the result doesn't come
    18      back in the given time period"""
    19
    20      timer = None
    21
    22 -    def __init__(self, other, timeout):
    23          """Wrap the passed deferred and return a new deferred that
    24          will timeout
    25
    26          @type other: a Deferred
    27          @param other: the deferred to wrap
    28          @type timeout: floating point number
    29          @param timeout: time, in seconds, to wait before failing the deferred
    30          """
    31          defer.Deferred.__init__(self)
    32          self.timer = reactor.callLater(timeout, self._timeout)
    33          other.chainDeferred(self)
    34
    35 -    def _timeout(self):
    36          "The wrapped deferred was too slow: fire the errback"
    37          if not self.called:
    38              self.timer = None
    39              self.errback(defer.TimeoutError())
    40
    41 -    def _startRunCallbacks(self, result):
    42          "We have a result, fire callbacks or cancel the timer"
    43          if self.timer:
    44              self.timer.cancel()
    45              self.timer = None
    46          if not self.called:
    47              defer.Deferred._startRunCallbacks(self, result)
    48
    49 -def timeout(deferred, timeInSeconds):
    50      "Utility method to wrap a deferred to timeout in timeInSeconds"
    51      return TimeoutDeferred(deferred, timeInSeconds)
    52