Yet Another WebIOPi+
 All Classes Namespaces Files Functions Variables Macros Pages
thread.py
Go to the documentation of this file.
1 import time
2 import signal
3 import threading
4 from webiopi.utils import logger
5 
6 RUNNING = False
7 TASKS = []
8 
9 class Task(threading.Thread):
10  def __init__(self, func, loop=False):
11  threading.Thread.__init__(self)
12  self.func = func
13  self.loop = loop
14  self.running = True
15  self.start()
16 
17  def stop(self):
18  self.running = False
19 
20  def run(self):
21  if self.loop:
22  while self.running == True:
23  self.func()
24  else:
25  self.func()
26 
27 def stop(signum=0, frame=None):
28  global RUNNING
29  if RUNNING:
30  logger.info("Stopping...")
31  RUNNING = False
32  for task in TASKS:
33  task.stop()
34 
35 
36 def runLoop(func=None, async=False):
37  global RUNNING
38  RUNNING = True
39  signal.signal(signal.SIGINT, stop)
40  signal.signal(signal.SIGTERM, stop)
41 
42  if func != None:
43  if async:
44  TASKS.append(Task(func, True))
45  else:
46  while RUNNING:
47  func()
48  else:
49  while RUNNING:
50  time.sleep(1)