I have a script that takes quite a long time to execute. Is there a way to run some code or call a function in case for example the user closes the window while the script is still running? Ideally I would like to run code to set a status as failure in the database.

You can divide the processing in small parts, for example process.php?part=1,2,3 and so on.
But you have to save the state of last processing progress in some place safe to access it next time script executes and continues from where it ended.
I cannot say much cause your question need to be more specific.