Package omero :: Package util :: Module concurrency
[hide private]
[frames] | no frames]

Source Code for Module omero.util.concurrency

  1  #!/usr/bin/env python 
  2  # 
  3  # OMERO Concurrency Utilities 
  4  # 
  5  # Copyright 2009 Glencoe Software, Inc.  All Rights Reserved. 
  6  # Use is subject to license terms supplied in LICENSE.txt 
  7  # 
  8   
  9  import os 
 10  import sys 
 11  import time 
 12  import atexit 
 13  import logging 
 14  import threading 
 15  import omero.util 
 16  import exceptions 
 17  import logging.handlers 
 18   
 19   
20 -def get_event(name = "Unknown"):
21 """ 22 Returns a threading.Event instance which is registered to be 23 "set" (Event.set()) on system exit. 24 """ 25 event = AtExitEvent(name=name) 26 atexit.register(event.setAtExit) 27 return event
28 29
30 -class AtExitEvent(threading._Event):
31 """ 32 threading.Event extension which provides an additional method 33 setAtExit() which sets "atexit" to true. 34 35 This class was introduced in 4.2.1 to work around issue #3260 36 in which logging from background threads produced error 37 messages. 38 """ 39
40 - def __init__(self, verbose = None, name = "Unknown"):
41 super(AtExitEvent, self).__init__(verbose) 42 self.__name = name 43 self.__atexit = False
44 45 name = property(lambda self: self.__name) 46 atexit = property(lambda self: self.__atexit) 47
48 - def setAtExit(self):
49 self.__atexit = True 50 super(AtExitEvent, self).set()
51
52 - def __repr__(self):
53 return "%s (%s)" % (super(AtExitEvent, self).__repr__(), self.__name)
54 55
56 -class Timer(threading._Timer):
57 """Based on threading._Thread but allows for resetting the Timer. 58 59 t = Timer(30.0, f, args=[], kwargs={}) 60 t.start() 61 t.cancel() # stop the timer's action if it's still waiting 62 63 # or 64 65 t.reset() 66 67 After excecution, the status of the run can be checked via the 68 "completed" and the "exception" Event instances. 69 """ 70
71 - def __init__(self, interval, function, args=None, kwargs=None):
72 if args is None: 73 args = [] 74 if kwargs is None: 75 kwargs = {} 76 threading._Timer.__init__(self, interval, function, args, kwargs) 77 self.log = logging.getLogger(omero.util.make_logname(self)) 78 self.completed = threading.Event() 79 self.exception = threading.Event() 80 self._reset = threading.Event()
81
82 - def reset(self):
83 self.log.debug("Reset called") 84 self._reset.set() # Set first, so that the loop will continue 85 self.finished.set() # Forces waiting thread to fall through
86
87 - def run(self):
88 while True: 89 self.finished.wait(self.interval) 90 if self._reset.isSet(): 91 self.finished.clear() 92 self._reset.clear() 93 self.log.debug("Resetting") 94 continue 95 if not self.finished.isSet(): 96 try: 97 self.log.debug("Executing") 98 self.function(*self.args, **self.kwargs) 99 self.completed.set() 100 self.finished.set() 101 except: 102 self.exception.set() 103 self.finished.set() 104 raise 105 break
106