小编典典

使用Flask运行计划时出现问题

flask

我需要在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)

运行此程序时,我想要“运行定期任务!” 每10秒打印一次。但是,这是我得到的输出。

 * Running on http://0.0.0.0:5000/
 * Restarting with reloader
Start time: 1417002869.99
Running periodic task!
Elapsed time: 10.0128278732
Running periodic task!
Elapsed time: 10.0126948357
Running periodic task!
Elapsed time: 20.0249710083
Running periodic task!
Elapsed time: 20.0247309208
Running periodic task!
Elapsed time: 30.0371530056
Running periodic task!
Elapsed time: 30.0369319916

显然,由于某种原因,任务似乎每10秒执行两次,而不是一次。但是,如果我仅单独运行任务计划程序,而不是与Flask一起运行(仅通过注释app.run()行),它将正常运行。

Start time: 1417003801.52
Running periodic task!
Elapsed time: 10.0126750469
Running periodic task!
Elapsed time: 20.0246500969
Running periodic task!
Elapsed time: 30.0366458893

这可能是什么原因?运行多个线程时将任务排队的方式是否存在问题?它仍然没有解释为什么为什么一次只安排两个任务。


阅读 413

收藏
2020-04-07

共1个答案

小编典典

使用重新加载器运行开发服务器时(默认为debug=True),模块执行两次,导致的两个实例t。你可以通过添加来验证这一点print(id(t))

解决此问题的最简单方法是传递use_reloader=Falseapp.run。你可以看到此答案,这是允许你使用重新加载器的替代解决方案。

2020-04-07