1#!/usr/bin/env python
2# -*- python-mode -*-
3# -*- coding: UTF-8 -*-
4
5## Copyright (C) 2012-2013  Daniel Pavel
6##
7## This program is free software; you can redistribute it and/or modify
8## it under the terms of the GNU General Public License as published by
9## the Free Software Foundation; either version 2 of the License, or
10## (at your option) any later version.
11##
12## This program is distributed in the hope that it will be useful,
13## but WITHOUT ANY WARRANTY; without even the implied warranty of
14## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15## GNU General Public License for more details.
16##
17## You should have received a copy of the GNU General Public License along
18## with this program; if not, write to the Free Software Foundation, Inc.,
19## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21from __future__ import absolute_import, division, print_function, unicode_literals
22
23from logging import getLogger, DEBUG as _DEBUG
24_log = getLogger(__name__)
25del getLogger
26
27from threading import Thread as _Thread
28
29try:
30	from Queue import Queue as _Queue
31except ImportError:
32	from queue import Queue as _Queue
33
34#
35#
36#
37
38class TaskRunner(_Thread):
39	def __init__(self, name):
40		super(TaskRunner, self).__init__(name=name)
41		self.daemon = True
42		self.queue = _Queue(16)
43		self.alive = False
44
45	def __call__(self, function, *args, **kwargs):
46		task = (function, args, kwargs)
47		self.queue.put(task)
48
49	def stop(self):
50		self.alive = False
51		self.queue.put(None)
52
53	def run(self):
54		self.alive = True
55
56		if _log.isEnabledFor(_DEBUG):
57			_log.debug("started")
58
59		while self.alive:
60			task = self.queue.get()
61			if task:
62				function, args, kwargs = task
63				assert function
64				try:
65					function(*args, **kwargs)
66				except:
67					_log.exception("calling %s", function)
68
69		if _log.isEnabledFor(_DEBUG):
70			_log.debug("stopped")
71