Flask结合APScheduler实现定时任务

1. 安装 flask_apscheduler

pip install Flask-APScheduler

2. 编写代码


from flask import Flask,render_template,flash,request,redirect,url_for
from flask_apscheduler import APScheduler
import datetime,os

#记录日志
def write_log(buf):
    print(buf)
    with open('test.txt', 'a') as f:
        f.write(buf+"\n")

app = Flask(__name__)

@app.route("/",methods=['GET','POST'])
def index():
    return "hello world"

def job_function():
    write_log("Hello World" + " " + str(datetime.datetime.now()))

def task():
    write_log("task start "+str(os.getpid()))
    scheduler = APScheduler()
    scheduler.init_app(app)
    #定时任务,每隔10s执行1次
    scheduler.add_job(func=job_function, trigger='interval', seconds=10, id='my_job_id')
    scheduler.start()

#写在main里面,IIS不会运行
task()

if __name__ == "__main__":
    app.run(debug=False,host="0.0.0.0",port="8000")

3. 参考资料

https://blog.csdn.net/kikaylee/article/details/73065032

4. 注意事项

IIS中部署的flask项目,不会运行__main__中的内容,需要将task放到外面。

你可能感兴趣的:(WEB,Python)