Skip to content

Instantly share code, notes, and snippets.

@chadselph
Last active April 21, 2022 10:20
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 19 You must be signed in to fork a gist
  • Save chadselph/4ff85c8c4f68aa105f4b to your computer and use it in GitHub Desktop.
Save chadselph/4ff85c8c4f68aa105f4b to your computer and use it in GitHub Desktop.
flask with "cron"-like loop
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', port=1337)
scheduler.stop()
@CWang24
Copy link

CWang24 commented Sep 15, 2015

I tried your code, it works, but why is the query_db() called twice in every 5 seconds?

@RafaAguilar
Copy link

Hi @chadselph, thanks for your code, it works like @CWang24 said, but really, it call the function twice.

edit:

The code is just fine, the code is flawless, what is called twice is the main function if you don't turn off the reloader. More

@naimo
Copy link

naimo commented Dec 16, 2015

Thanks

@shenpei1989
Copy link

call the function twice, it's because 'debug=True', you can use 'app.run(host='0.0.0.0', debug=False, port=1337)' or 'app.run(host='0.0.0.0', debug=True, port=1337, use_reloader=False)' to solve this problem.

@sunjos
Copy link

sunjos commented Mar 9, 2018

Good,THKS

@kxbin
Copy link

kxbin commented Oct 19, 2021

Good,THKS. But why import Thread,This doesn't seem to use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment