Created
December 18, 2024 14:30
-
-
Save mariocesar/2387e9f467c052a87cfdb400d2e0f807 to your computer and use it in GitHub Desktop.
Celery. Reduce risk of idle connections by closing connections.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from celery import Celery | |
from celery.signals import worker_shutdown, task_postrun | |
from django.db import connections | |
app = Celery() | |
... | |
@worker_shutdown.connect | |
def close_db_connections(sender, **kwargs): | |
for conn in connections.all(initialized_only=True): | |
conn.close() | |
@task_postrun.connect | |
def close_db_connections_after_task_completed(sender, **kwargs): | |
for conn in connections.all(initialized_only=True): | |
conn.close() | |
# This is will be call on Forced Stops | |
def handle_sigterm(signum, frame): | |
for conn in connections.all(initialized_only=True): | |
conn.close() | |
signal.signal(signal.SIGTERM, handle_sigterm) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment