Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule a function to run every hour on Flask?

I have a Flask web hosting with no access to cron command.

How can I execute some Python function every hour?

like image 957
RomaValcer Avatar asked Oct 19 '22 23:10

RomaValcer


People also ask

How do I schedule a task in flask?

To begin, let's first set up the Flask framework with Celery. Save this python script as app.py in the main project directory, and in your terminal, run: python ~/celery-scheduler/app.py . Now go to http://localhost:5000/. If everything is running fine, you should see “Hello, Flask is up and running!”

How do you run a function in flask?

Debug modeA Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes.

How do you keep a flask server running?

Make sure, you close the terminal and not press Ctrl + C. This will allow it to run in background even when you log out. To stop it from running , ssh in to the pi again and run ps -ef |grep nohup and kill -9 XXXXX where XXXX is the pid you will get ps command.


2 Answers

You can use BackgroundScheduler() from APScheduler package (v3.5.3):

import time
import atexit

from apscheduler.schedulers.background import BackgroundScheduler


def print_date_time():
    print(time.strftime("%A, %d. %B %Y %I:%M:%S %p"))


scheduler = BackgroundScheduler()
scheduler.add_job(func=print_date_time, trigger="interval", seconds=60)
scheduler.start()

# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())

Note that two of these schedulers will be launched when Flask is in debug mode. For more information, check out this question.

like image 160
tuomastik Avatar answered Oct 21 '22 13:10

tuomastik


I'm a little bit new with the concept of application schedulers, but what I found here for APScheduler v3.3.1 , it's something a little bit different. I believe that for the newest versions, the package structure, class names, etc., have changed, so I'm putting here a fresh solution which I made recently, integrated with a basic Flask application:

#!/usr/bin/python3
""" Demonstrating Flask, using APScheduler. """

from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask

def sensor():
    """ Function for test purposes. """
    print("Scheduler is alive!")

sched = BackgroundScheduler(daemon=True)
sched.add_job(sensor,'interval',minutes=60)
sched.start()

app = Flask(__name__)

@app.route("/home")
def home():
    """ Function for test purposes. """
    return "Welcome Home :) !"

if __name__ == "__main__":
    app.run()

I'm also leaving this Gist here, if anyone have interest on updates for this example.

Here are some references, for future readings:

  • APScheduler Doc: https://apscheduler.readthedocs.io/en/latest/
  • daemon=True: https://docs.python.org/3.4/library/threading.html#thread-objects
like image 97
ivanleoncz Avatar answered Oct 21 '22 12:10

ivanleoncz