Skip to content

Instantly share code, notes, and snippets.

@mariocesar
Created December 18, 2024 14:30
Show Gist options
  • Save mariocesar/2387e9f467c052a87cfdb400d2e0f807 to your computer and use it in GitHub Desktop.
Save mariocesar/2387e9f467c052a87cfdb400d2e0f807 to your computer and use it in GitHub Desktop.
Celery. Reduce risk of idle connections by closing connections.
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