-
-
Save kyle-go/9db14ce1ac5a96409b0d to your computer and use it in GitHub Desktop.
flask with "cron"-like loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, render_template, jsonify, request | |
from threading import Timer, Thread | |
from time import sleep | |
app = Flask(__name__) | |
@app.route("/api/<method>") | |
def api(method): | |
data = { | |
'foo': 'bar', | |
'method': method | |
} | |
response = jsonify(data) | |
response.status_code = 200 | |
return response | |
class Scheduler(object): | |
def __init__(self, sleep_time, function): | |
self.sleep_time = sleep_time | |
self.function = function | |
self._t = None | |
def start(self): | |
if self._t is None: | |
self._t = Timer(self.sleep_time, self._run) | |
self._t.start() | |
else: | |
raise Exception("this timer is already running") | |
def _run(self): | |
self.function() | |
self._t = Timer(self.sleep_time, self._run) | |
self._t.start() | |
def stop(self): | |
if self._t is not None: | |
self._t.cancel() | |
self._t = None | |
def query_db(): | |
print "IM QUERYING A DB" | |
if __name__ == "__main__": | |
scheduler = Scheduler(5, query_db) | |
scheduler.start() | |
app.run(host='0.0.0.0', debug=True, port=1337) | |
scheduler.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what is called twice is the main function if you don't turn off the reloader.
http://stackoverflow.com/questions/25504149/why-does-running-the-flask-dev-server-run-itself-twice