Categories
Python Answers

How to add a background thread to Python Flask?

Spread the love

Sometimes, we want to add a background thread to Python Flask.

In this article, we’ll look at how to add a background thread to Python Flask.

How to add a background thread to Python Flask?

To add a background thread to Python Flask, we can use the flask_apscheduler package.

To install it, we run

pip install Flask-APScheduler

Then we run it by writing

from flask import Flask
from flask_apscheduler import APScheduler


class Config(object):
    JOBS = [
        {
            'id': 'job1',
            'func': 'jobs:job1',
            'args': (1, 2),
            'trigger': 'interval',
            'seconds': 10
        }
    ]

    SCHEDULER_API_ENABLED = True


def job1(a, b):
    print(str(a), str(b))

if __name__ == '__main__':
    app = Flask(__name__)
    app.config.from_object(Config())

    scheduler = APScheduler()
    scheduler.init_app(app)
    scheduler.start()

    app.run()

to call app.config.from_object to add the job config in the Config instance.

Next, we create the scheduler APScheduler instance.

And then we call init_app with app to add the scheduler to the app.

Then we call start to start the scheduler.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *