threading.Thread()
is one of the standard libraries in Python, providing a way to perform asynchronous tasks in the background easily.
It can be used without installing any external libraries and is useful for implementing simple parallel processing.
1. When to Use
- When the task takes a long time but failure is not catastrophic
- When you want to quickly respond to users on a web server and handle the remaining post-processing separately
- When you want to implement lightweight asynchronous processing before introducing heavy systems like Celery or Redis
2. Criteria for Use
Situation | Recommendation |
---|---|
When you want to respond quickly | ✅ Suitable for use |
When the task duration is short or moderate | ✅ Suitable for use |
When failure of the task is not critical | ✅ Suitable for use |
When stability and monitoring are important | ❌ Recommended to use something like Celery |
When database transactions need to be handled carefully | ⚠️ Caution needed with ORM usage |
3. Example of Use
import threading
import time
def background_task():
print("Starting background task")
time.sleep(3)
print("Background task completed")
# Execute thread
thread = threading.Thread(target=background_task)
thread.start()
print("Main thread finished")
target=function_name
: Specifies the function to execute
You can pass arguments withargs=(arg1, arg2, ...)
The thread will only run when.start()
is called
4. Notes for Use in Django
- Django's ORM is not thread-safe, so be careful with DB transaction handling
- Exceptions raised inside threads are not automatically caught → Always use
try/except
- If you need to use request-related information inside a thread, ensure its validity (e.g., request.user, etc.)
- It is recommended to implement logging to detection of post-processing failures
5. Summary
Advantages | Disadvantages |
---|---|
Convenience (no installation needed) | No automatic retries/monitoring |
Improved response speed | Potential conflicts with ORM |
Possibility of ultra-lightweight asynchronous processing | Difficulty managing task failures |
6. Jesse's Comment
threading.Thread()
is an excellent way to perform asynchronous processing quickly without putting too much load on the server.
As a middle step before migrating to Celery, it can be a sufficiently powerful tool in practice.
Add a New Comment