def __init__(self):
		super(TaskScheduler,self).__init__()
		self.task_dao_json = TaskDAOJSON()
		self.check_event = threading.Event()
		self.task_queue = queue.PriorityQueue()
		self.interrupted = False
		self.load_startup_tasks()
class TaskScheduler(threading.Thread):

	def __init__(self):
		super(TaskScheduler,self).__init__()
		self.task_dao_json = TaskDAOJSON()
		self.check_event = threading.Event()
		self.task_queue = queue.PriorityQueue()
		self.interrupted = False
		self.load_startup_tasks()

	def init(self, condition_engine):
		self.condition_engine = condition_engine
		self.running = True
		self.start() #only start when properly initialized

	def load_startup_tasks(self):
		task_list = self.task_dao_json.load_tasks()

		for startup_task in task_list:
			time = None
			if(startup_task['isFixedEvent']):
				time = time_utils.to_seconds(startup_task['time'])
			else:
				time = time_utils.to_future_time(startup_task['time'])

			task = (time, startup_task['command'])
			self.add_task(task)

	def process_next_task(self):
		command = self.task_queue.get()[1] #dont care about time anymore, just take the message
		logger.info('Executing task: ' + str(command))
		self.condition_engine.add_message(('None', command)) # node label is 'None' to indicate that it did not come from a node

	def add_task(self, task):
		self.task_queue.put(task)
		self.check_event.set()
		self.interrupted = True
		logger.info('Added a task to the task scheduler: ' + str(task))

	def stop(self):
		self.interrupted = True
		self.running = False
		self.check_event.set()

	def run(self):
		while self.running:
			self.check_event.clear()
			if self.task_queue.empty() == False:
				highest_priority_task = self.task_queue.get() #get highest priority item from queue as a tuple (time, command)
				sleep_delay = (highest_priority_task[0] - datetime.datetime.now()).total_seconds() #event time - current time = delta time
				logger.info('Sleeping task thread for: ' + str(sleep_delay) + ' seconds') #debugging
				self.task_queue.put(highest_priority_task) #put the task back
				self.check_event.wait(sleep_delay)
				self.interrupted = False
			else:
				self.check_event.wait()
			logger.info('Woke up to execute a task')

			if self.interrupted == False and self.task_queue.empty() == False: # sleep wasn't interupted by addition of new item
				logger.info('Processing the next task')
				self.process_next_task() #otherwise, return to recalculating sleep period
			self.interrupted = False