Execute python code just before blender exits

Hey guys I want to execute code just before Blender exits, in my case I just want to close a socket and do some clean up. I want the code to run when users exits Blender from Blender menu, or by a shortcut , or by the user clicking on a button.

There is no app handler for this, i can only think of context managers (with-block)

Python has an atexit module for this:

import atexit

def onexit():


yeah tried , did not work cause I use threads. My problem was I wanted to close a socket before blender exit, but I manage to find another way and make the socket reusable so now it does not freeze blender on exit.