Overview
Yup, it can be done. Achieving this is possible through the OnClose callback function on game. This function has no parameters, and holds ROBLOX's standard form of creating callbacks: Object.Callback = function() end - basically the same as setting a function within a dictionary.
The OnClose function is called when the game invokes a shutdown. However, the code inside the function will run, delaying the shutdown until the function has terminated. This is also known as a yielded callback.
Saving
Most of the time this is used to ensure a safe way that player data, or anything being saved through DataStoreService is requested before a game is completely shutdown.
Timeout
For good reason, there is a 30 second timeout you're limited to while the shutdown is undergoing it's delay from the OnClose function. This means no matter what, the game will completely shutdown after 30 seconds, even if you were to say something like this:
game.OnClose = function()
wait(10000000)
end
But, if you're using this with the intention of saving something, that should be plenty of time.
**One time use **
Since this is a yielded callback, you can only have one of these OnClose listeners created per-server. This means attempting to use game.OnClose in another script, or multiple times, will result in this error message: > OnClose is already set
For this reason, it is a one-time use creation just like every other yielded callback. So think wisely about how you use it if you're going to be dependent on it for more than just delaying the shutdown of the server.
Sources
ROBLOX Wiki - OnClose: http://wiki.roblox.com/index.php?title=API:Class/DataModel/OnClose
Questions
If you have any questions, just let leave a comment or send me a PM for further detail.
2 comments
Very instructive, but have you thought of making it to where using a while loop and putting waits before, inside, and after the function has ended could possibly do?
Well it's not exactly a matter of waits or loops, the entire thread itself is timed.