Skip to content

Instantly share code, notes, and snippets.

@i-like-bikes
Created October 15, 2018 06:05
Show Gist options
  • Save i-like-bikes/b2a1cb15d17584ddfd127d7e61e5890d to your computer and use it in GitHub Desktop.
Save i-like-bikes/b2a1cb15d17584ddfd127d7e61e5890d to your computer and use it in GitHub Desktop.
# https://stackoverflow.com/questions/11810461/how-to-perform-periodic-task-with-flask-in-python
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# initialise Flask app
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
db.create_all()
@app.route('/<name>/<email>')
def hello_world(name, email):
u = User(username=name, email=email)
db.session.add(u)
db.session.commit()
return 'hello, world :('
def test_job():
print(User.query.all())
print('I am working...')
if __name__ == '__main__':
scheduler = BackgroundScheduler()
job = scheduler.add_job(test_job, 'interval', seconds=10)
scheduler.start()
app.run()
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
* Serving Flask app "untitled" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[<User 'robert'>]
I am working...
[<User 'robert'>]
I am working...
127.0.0.1 - - [15/Oct/2018 17:02:42] "GET /mahmoud/qwer23 HTTP/1.1" 200 -
[<User 'robert'>, <User 'mahmoud'>]
I am working...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment