Universal timer

I’m trying to create a universal timer across all game instances (and new ones) that stays in sync with each other, and resets every 7 days. I’ve looked for over 2 hours now and I can’t find an answer/what I should be using to do this. All I’ve seen is os but I don’t think it’s consistent while a server instance is offline?

Use os.time(). It is the number of seconds since the unix epoch in UTC time. Modulo it by 7 days.

The current time of this timer in seconds would be

os.time() % (60 * 60 * 24 * 7) -- 60 secs * 60 min * 24 hour * 7 days
2 Likes
local DataStoreService = game:GetService("DataStoreService")
local TimerDataStore = DataStoreService:GetDataStore("UniversalTimerDataStore")

local TIMER_RESET_INTERVAL = 7 * 24 * 60 * 60 -- 7 days in seconds

local function syncTimer()
    local currentTime = os.time()
    local timerData = TimerDataStore:GetAsync("TimerData")

    if not timerData then
        timerData = currentTime
        TimerDataStore:SetAsync("TimerData", timerData)
    end

    local elapsedTime = currentTime - timerData
    if elapsedTime >= TIMER_RESET_INTERVAL then
        -- Reset the timer
        timerData = currentTime
        TimerDataStore:SetAsync("TimerData", timerData)
    end

    -- Broadcast the current timer data to all game instances
    game:GetService("ReplicatedStorage"):FireAllClients(timerData)
end

-- Run the syncTimer function every few seconds
game:GetService("RunService").Heartbeat:Connect(function()
    syncTimer()
end)

What does the % mean in the statement?

% is the modulo operator. It gives you the remainder of division, which allows you to have a cycle without any additional math.

2 Likes

No. Not how it works. Also, this solution would be way more unnecessarily complex than the solution already provided.

local DataStoreService = game:GetService(“DataStoreService”)
local TimerDataStore = DataStoreService:GetDataStore(“UniversalTimerDataStore”)

Why are you posting a nonsense AI answer?

1 Like

What he needs is a help so any data source as long as it is suggested to him is fine.
Anyone who has ever used Al tools knows that it is a piece of code written in Al and if I credit the source as Al it will not respect the person to whom Al references the source code.
And it is merely a suggestion.

probably a dumb question, but i copied the code to experiment with from one of the replies but it errors? im just very confused on how this works
image

image

Crude example:

while task.wait(1) do 
local currentTime = os.time() % (60*60*24*7)
(use the currentTime variable)
end
2 Likes

What is this for? Are you doing a game-wide event? If so, please use the Roblox event system: