Skip to content

Instantly share code, notes, and snippets.

@kageurufu
Created May 20, 2015 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kageurufu/861c666b5ad118510454 to your computer and use it in GitHub Desktop.
Save kageurufu/861c666b5ad118510454 to your computer and use it in GitHub Desktop.
import time
from threading import Thread, Event
import Queue
from flask import Flask, request
class LoopThread(Thread):
def __init__(self, stop_event, interrupt_queue):
self.stop_event = stop_event
self.interrupt_queue = interrupt_queue
Thread.__init__(self)
def run(self):
while not self.stop_event.is_set():
self.loop_process()
self.process_interrupts()
def loop_process(self):
print("Processing!")
time.sleep(3)
def process_interrupts(self):
try:
interrupt = self.interrupt_queue.get_nowait()
self.process_single_interrupt(interrupt)
except Queue.Empty:
pass
def process_single_interrupt(self, interrupt):
if interrupt == "interrupt_1":
print("Interrupt reason string 1")
elif interrupt == 2:
print ("Interrupt reason int 2")
else:
print("Invalid interrupt: %s" % interrupt)
STOP_EVENT = Event()
INTERRUPT_QUEUE = Queue.Queue()
thread = LoopThread(STOP_EVENT, INTERRUPT_QUEUE)
app = Flask(__name__)
@app.route("/interrupt/1")
def interrupt1():
INTERRUPT_QUEUE.put("interrupt_1")
return "OK", 200
@app.route("/interrupt/2")
def interrupt2():
INTERRUPT_QUEUE.put(2)
return "OK", 200
@app.route("/interrupt/3")
def interrupt3():
INTERRUPT_QUEUE.put(3)
return "OK", 200
# http://flask.pocoo.org/snippets/67/
def shutdown_server():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
@app.route("/shutdown")
def shutdown():
STOP_EVENT.set()
thread.join()
shutdown_server()
return "OK", 200
if __name__ == '__main__':
thread.start()
app.run("0.0.0.0", 9999)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment