How to Create Background Tasks in Flask Easily
In Flask, you can create a background task by using the
threading module to run a function in a separate thread without blocking the main app. For more complex or long-running tasks, use a task queue like Celery to handle background jobs asynchronously.Syntax
To create a background task in Flask using threading, you start a new thread that runs your function separately from the main request thread. This lets your app respond immediately while the task runs in the background.
threading.Thread(target=your_function): Creates a new thread to runyour_function.thread.start(): Starts the thread so the function runs asynchronously.
python
from threading import Thread def background_task(): print('Task started') # Your long-running code here # Start background task thread = Thread(target=background_task) thread.start()
Output
Task started
Example
This example shows a Flask app that starts a background task when you visit the /start-task route. The task runs in a separate thread and prints messages without blocking the web response.
python
from flask import Flask, jsonify from threading import Thread import time app = Flask(__name__) def background_task(): for i in range(5): print(f'Background task running step {i + 1}') time.sleep(1) print('Background task completed') @app.route('/start-task') def start_task(): thread = Thread(target=background_task) thread.start() return jsonify({'message': 'Background task started!'}), 202 if __name__ == '__main__': app.run(debug=True)
Output
Background task running step 1
Background task running step 2
Background task running step 3
Background task running step 4
Background task running step 5
Background task completed
Common Pitfalls
Common mistakes when creating background tasks in Flask include:
- Not using threads or task queues, causing the app to freeze during long tasks.
- Accessing Flask's
requestorappcontext inside the background thread without proper context management. - Not handling exceptions inside the background task, which can silently fail.
Always start threads properly and avoid using Flask globals inside background tasks unless you push the app context.
python
from flask import Flask, request from threading import Thread app = Flask(__name__) def background_task(): # WRONG: accessing request directly in thread causes error print(request.args.get('param')) @app.route('/wrong') def wrong(): thread = Thread(target=background_task) thread.start() return 'Started wrong task' # Correct way with app context def background_task_with_context(app, param): with app.app_context(): print(f'Param is {param}') @app.route('/right') def right(): param = request.args.get('param') thread = Thread(target=background_task_with_context, args=(app, param)) thread.start() return 'Started right task'
Quick Reference
Tips for background tasks in Flask:
- Use
threading.Threadfor simple, short background jobs. - Use
Celerywith a message broker like Redis for complex or long-running tasks. - Manage Flask app context inside threads if you access Flask globals.
- Handle exceptions inside background tasks to avoid silent failures.
- Return immediate responses from routes to keep the app responsive.
Key Takeaways
Use Python's threading to run background tasks without blocking Flask responses.
For complex tasks, integrate Celery with Flask for reliable asynchronous processing.
Always manage Flask app context inside background threads when accessing Flask-specific variables.
Handle errors inside background tasks to prevent silent failures.
Return responses immediately from routes to keep your Flask app responsive.