<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def run(self, background=False):
 """Runs `on_startup`, `main` and `on_shutdown`, blocking until finished, unless background is set."""

        if self.__bgthread:
            raise Exception('run has already been called (since last stop)')
        self.__shutdown.clear()
        if background:
            self.__bgthread = Thread(target=self.__run, name=('bg_' + self.__client.agent_id))
            self.__bgthread.daemon = True
            self.__bgthread.start()
        else:
            self.__run()