How do you add a background thread to flask in Python

0 votes
I'm trying to write a game server to try out flask. The game exposes an API via REST to users.

It's easy for users to perform actions and query data, however I'd like to service the "game world" outside the loop to update game entities, etc.

 Given that Flask is so cleanly implemented, I'd like to see if there's a Flask way to do this. Need some help!
Nov 19, 2018 in Python by Anirudh
• 2,080 points

1 answer to this question.

0 votes

The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.

import threading
import atexit
from flask import Flask

POOL_TIME = 5 #Seconds

# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()

def create_app():
    app = Flask(__name__)

    def interrupt():
        global yourThread

    def doStuff():
        global commonDataStruct
        global yourThread
        with dataLock:
        # Do your stuff with commonDataStruct Here

        # Set the next thread to happen
        yourThread = threading.Timer(POOL_TIME, doStuff, ())

    def doStuffStart():
        # Do initialisation stuff here
        global yourThread
        # Create your thread
        yourThread = threading.Timer(POOL_TIME, doStuff, ())

    # Initiate
    # When you kill Flask (SIGTERM), clear the trigger for the next thread
    return app

app = create_app()          

Call it from Gunicorn with something like this:

gunicorn -b --log-config log.conf myfile:app

Hope this will help!

If you need to know more about Python, join Python certification course online today.


answered Nov 19, 2018 by Nymeria
• 3,520 points

Can you re-start the background task from specific routes throughout your app? I want a background task that starts based on the user who logs in into my app. For this, I believe I would need to access flask_login.current_user. How do I do that? Also, I want the background task to start once the user logs in, not before.

Your help would be very appreciated!

Thanks in advance

Hi, @Daniel Gutierrez,

Do you want a whole source code where access flask_login.current_user would be mention according to your query?

Hello, @Danial,

You can use this below given to login first and then start with background task:

def refresh_user():
    auth_methods = { am for am in current_app.auth_methods}
    user_auth_method = auth_methods[flask_login.current_user.authmethod]
    if user_auth_method.refresh(flask_login.current_user):
        current_app.logger.debug("Marking '{}' as fresh".format(
        # Call the original endpoint
        view = current_app.view_functions[request.endpoint]
        return view(**request.view_args)
        original_url = url_for(request.endpoint, **request.view_args)
        return redirect(url_for('login.login', next=original_url,

Related Questions In Python

0 votes
1 answer
0 votes
1 answer

How to add a new line in Python?

You can use '\n' for a next ...READ MORE

answered May 2, 2018 in Python by aayushi
• 750 points
+2 votes
1 answer

How do you make a block comment in python?

''' This is a multiline comment. I ...READ MORE

answered Aug 23, 2018 in Python by Priyaj
• 58,140 points
0 votes
2 answers

How do I connect to a MySQL Database in Python?

connect mysql database with python import MySQLdb db = ...READ MORE

answered Mar 28, 2019 in Python by rajesh
• 1,230 points
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,365 views
0 votes
0 answers
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
0 votes
1 answer

List comprehension on a nested list - How to do it in Python?

Not sure what your desired output is, ...READ MORE

answered Nov 21, 2018 in Python by Nymeria
• 3,520 points
0 votes
1 answer

Question on PyQt: How to connect a signal to a slot to start a background operation in Python

It shouldn't matter whether the connection is ...READ MORE

answered Nov 27, 2018 in Python by Nymeria
• 3,520 points