Skip to content

Instantly share code, notes, and snippets.

@dmd

dmd/-

Created September 24, 2015 02:08
Show Gist options
  • Save dmd/887bd294c95eb94e0564 to your computer and use it in GitHub Desktop.
Save dmd/887bd294c95eb94e0564 to your computer and use it in GitHub Desktop.
import os
import sys
import imp
import re
from os.path import join as pjoin
from subprocess import check_output
from flask import Flask, jsonify, abort, request
from flask.ext.api import status
import json
from uuid import uuid4
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler import events
from time import sleep
import Queue
import logging
logging.basicConfig()
app = Flask(__name__)
jobstatus = {}
scheduler = BackgroundScheduler()
#scheduler.start()
messages = {}
completion = {}
@app.route('/')
def hello_world():
return 'hi'
jlen=10
def longrunner(job_id):
messages[job_id].put('started'.format(job_id))
#print('start')
for i in range(jlen):
sleep(2)
messages[job_id].put('did {}'.format(i))
completion[job_id] = (i+1)/float(jlen)
# if i == 3:
# raise AssertionError
messages[job_id].put('stopped'.format(job_id))
@app.route('/job/start')
def jobstart():
job_id = str(uuid4())[0:2]
messages[job_id] = Queue.Queue()
job = scheduler.add_job(lambda: longrunner(job_id), id=job_id)
return job.id
@app.route('/job/status/<job_id>')
def jobstatus(job_id):
msgs = []
while not messages[job_id].empty():
msgs.append(messages[job_id].get())
return jsonify(completion=completion[job_id], messages=msgs)
def job_listener(event):
job_id = event.job_id
if event.code == events.EVENT_JOB_EXECUTED:
print ("executed")
if event.code == events.EVENT_JOB_ADDED:
print ("added")
if event.code == events.EVENT_JOB_ERROR:
print ("got error: {}".format(str(type(event.exception))))
# while not messages[job_id].empty():
# get_ = "msg from job '%completion': '%completion'" % (job_id, messages[job_id].get())
# print get_
scheduler.add_listener(job_listener,
events.EVENT_JOB_EXECUTED |
events.EVENT_JOB_ERROR |
events.EVENT_JOB_ADDED)
scheduler.start()
if __name__ == '__main__':
app.run(port=8888, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment