✓ Accepted answer
The way people are answering this so far is incorrect. You're not delaying server shut down when you use :BindToClose. It just runs all the functions you place inside of it, also called "bound functions" in the article about it, in less than 30 seconds before the server shuts down. For example, the server may shut down before your PlayerRemoving function runs. If you keep that function outside of the :BindToClose but also copy and paste it into :BindToClose you will ensure that the PlayerRemoving function will run, no matter what happens.
Example:
game.Players.PlayerRemoving:Connect(function(player)
local data = {}
DataStore:SetAsync(player.UserId, data)
end)
game:BindToClose(function()
for _, player in pairs(game.Players:GetPlayers()) do
local data = {}
DataStore:SetAsync(player.UserId, data)
end
end)
(I used some bad habits in this script, so don't actually use it for your game if you're trying to save data. I'm just trying to show you in the quickest way possible.)
:BindToClose will run 30 seconds before the server shuts down. If the server isn't going to shut down, players leaving are not going to be affected by it. The original PlayerRemoving function will run for them. This is why you want both PlayerRemoving and :BindToClose together. Usually, the server shuts down when there are no players left in the server. Sometimes, however, it can shut down unexpectedly. If there is one player left in the server and they leave, it is possible that the server will shut down before it finishes saving their data. This could also happen while you're playing solo in Roblox Studio. I ran into this issue as well, and my data is saving now all thanks to :BindToClose.
2 comments
So if I shut the server down for an update, lets say, will :BindToClose() fire?
Sorry about the late answer but yes, that's when it will fire.