#!/usr/bin/env python 
# Background.py
#
#   Copyright (C) 2009 Diamond Light Source, Graeme Winter
#
#   This code is distributed under the BSD license, a copy of which is 
#   included in the root directory of this package.
#
# Code to allow background (i.e. threaded) running of tasks.

import threading, exceptions

class Background(threading.Thread):
    '''A class to allow background operation.'''

    def __init__(self, o, m, a = None):
        '''Create a thread to call o.m(a).'''

        threading.Thread.__init__(self)

        if not hasattr(o, m):
            raise RuntimeError, 'method missing from object'

        self._object = o
        self._method = m
        self._arguments = a
        self._exception = None

        return

    def run(self):
        '''Run o.m with arguments a in background.'''

        task = getattr(self._object, self._method)

        try:
            if self._arguments:
                task(self._arguments)
            else:
                task()
        except exceptions.Exception, e:
            self._exception = e

    def stop(self):
        '''Rejoin the thread.'''

        self.join()
        if self._exception:
            raise self._exception
