Trying to create a system where the players can make things, but it will take for example 1 hour, so I dont expect them to stay ingame or so, How can I schedule or something like that.
I’m just spit-balling an idea here.
You can use DateTime.now().UnixTimestamp and save it in a player’s datastore, then when the player rejoins you can do:
local timeSinceLastLoggedIn = DateTime.now().UnixTimestamp - savedTimestamp
-- (where savedTimestamp is the previously saved DateTime.now().UnixTimestamp in datastore)
2 Likes
Try this
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("TimeStore")
local function SaveLastTime(player: Player)
local key = tostring(player.UserId)
local timeValue = os.time()
local attempts = 5
local delay = 0.5
for i = 1, attempts do
local success, errorMessage = pcall(function()
DataStore:SetAsync(key, timeValue)
end)
if success then
return
else
task.wait(delay)
delay *= 2
end
end
end
local function LoadLastTime(player: Player)
local key = tostring(player.UserId)
local attempts = 10
local delay = 0.1
for i = 1, attempts do
local success, data = pcall(function()
return DataStore:GetAsync(key)
end)
if success then
return data
else
task.wait(delay)
delay = math.min(delay * 2, 1)
end
end
return nil
end
game:BindToClose(function()
local players = game.Players:GetPlayers()
local saveTasks = {}
for _, player in ipairs(players) do
table.insert(saveTasks, task.spawn(function()
SaveLastTime(player)
end))
end
local startTime = os.clock()
for _, taskObj in ipairs(saveTasks) do
if os.clock() - startTime < 15 then
coroutine.resume(taskObj)
else
break
end
end
end)
game.Players.PlayerAdded:Connect(function(player: Player)
local lastTime = LoadLastTime(player)
if lastTime then
local currentTime = os.time()
local timeDiff = currentTime - lastTime
local totalMinutes = math.floor(timeDiff / 60)
local days = math.floor(timeDiff / 86400)
local hours = math.floor((timeDiff % 86400) / 3600)
local minutes = math.floor((timeDiff % 3600) / 60)
local seconds = math.floor(timeDiff % 60)
local detailedMessage = string.format(
"Offline counter: %d, %02d h, %02d m, %02d s",
days, hours, minutes, seconds
)
local minutesMessage = string.format("Player offline: %d m", totalMinutes)
print(detailedMessage)
print(minutesMessage)
end
end)
game.Players.PlayerRemoving:Connect(SaveLastTime)
This code prints to the console how many minutes the player was offline.
2 Likes
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.