schedule with flask microframework
Hi! how can i use schedule as a cron job with flask microframework? This is the answer i found on stackoverflow
# -*- coding: utf-8 -*-
"""
This script is a simple example you can use to schedule task with flask
microframework and schedule (https://github.com/dbader/schedule).
I've found it on on stackoverflow!
"""
import time
import schedule
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, use_reloader=False)
What are you trying to do? Do you want to have a flask API that can schedule jobs on command? For that you could add something like this:
def some_job():
print("This job was scheduled from flask")
@app.route('/schedule/every/<int:count>/<period>')
def add_to_schedule(count=1, period=None):
job = schedule.every(count)
if count == 1:
if period == 'day':
job = job.day
elif period == 'hour':
job = job.hour
elif period == 'minute':
job = job.minute
elif period == 'second':
job = job.second
else:
return "Invalid period " + period
else:
if period == 'day':
job = job.days
elif period == 'hour':
job = job.hours
elif period == 'minute':
job = job.minutes
elif period == 'second':
job = job.seconds
else:
return "Invalid period " + period
job.do(some_job)
return "OK"
And you could add more parameters and whatnot as necessary. Hope this helps!
thanks
@dylwhich I tired it but it did not work for me. Do I have to add something to main. here is my code
import schedule
import time
app = Flask(__name__)
def some_job():
print("This job was scheduled from flask")
@app.route('/schedule/every/<int:count>/<period>')
def add_to_schedule(count=1, period=None):
job = schedule.every(1).seconds.do(some_job)
return "OK"
if __name__ == "__main__":
app.run(debug=True)
You are missing the worker thread part in main. It is neccessary because this thread will call your functions. Right now there is no such thread in your app.
I want to do something similar to the example provided by @abdounasser202 and not use an endpoint like @dylwhich mentioned. I want to schedule a task in the background with Flask is started. Any help ?