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