Package Products :: Package ZenHub :: Package services :: Module Procrastinator |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenHub.services.Procrastinator

     1  ##############################################################################
     2  #
     3  # Copyright (C) Zenoss, Inc. 2007, 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  import logging
    12  from twisted.internet import reactor, defer
    13
    14
    15  log = logging.getLogger('zen.Procrastinator')
    16
    17
    18 -class Procrastinate(object):
    19      "A class to delay executing a change to a device"
    20
    21      _DO_LATER_DELAY = 5
    22      _DO_NOW_DELAY = 0.05
    23
    24 -    def __init__(self, cback):
    25          self.cback = cback
    26          self.devices = set()
    27          self.timer = None
    28          self._stopping = False
    29          self._stopping_deferred = defer.Deferred()
    30
    31 -    def clear(self):
    32          self.devices = set()
    33
    34 -    def stop(self):
    35          self._stopping = True
    36          if not self.devices:
    37              return defer.succeed(True)
    38          log.debug("Returning stopping deferred")
    39          d, self._stopping_deferred = self._stopping_deferred, None
    40          return d
    41
    42 -    def doLater(self, device = None):
    43          if not self._stopping:
    44              if self.timer and not self.timer.called:
    45                  self.timer.cancel()
    46              self.devices.add(device)
    47              self.timer = reactor.callLater(Procrastinate._DO_LATER_DELAY, self._doNow)
    48
    49 -    def _doNow(self, *unused):
    50          if self.devices:
    51              device = self.devices.pop()
    52              self.cback(device)
    53              if self.devices:
    54                  reactor.callLater(Procrastinate._DO_NOW_DELAY, self._doNow)
    55              elif self._stopping:
    56                  log.debug("Callback to _stopping_deferred")
    57                  self._stopping_deferred.callback(None)
    58