我需要在Flask应用程序上定期运行某个任务.我决定使用一个简单的库 - Schedule(https://github.com/dbader/schedule)来做这件事.我在主应用程序线程的单独线程上运行任务调度程序.这是相关的代码段.
import schedule
import time
from flask import Flask, request
from threading import Thread
app = Flask(__name__)
start_time = time.time()
def run_every_10_seconds():
print("Running periodic task!")
print "Elapsed time: " + str(time.time() - start_time)
def run_schedule():
while 1:
schedule.run_pending()
time.sleep(1)
@app.route('/', methods=['GET'])
def index():
return '<html>test</html>'
if __name__ == '__main__':
schedule.every(10).seconds.do(run_every_10_seconds)
t = Thread(target=run_schedule)
t.start()
print "Start time: " + str(start_time)
app.run(debug=True, host='0.0.0.0', port=5000)
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我想要'运行定期任务!' 每10秒打印一次.但是,这是我得到的输出.
* Running on http://0.0.0.0:5000/
* Restarting with reloader
Start time: 1417002869.99 …Run Code Online (Sandbox Code Playgroud)