Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Can someone help with the logic behind a "global" timer?

Asked by 8 years ago

Let's say, for instance, that I want to give a player a certain amount of time, for instance, 2 hours (7200 seconds). I want this to apply across servers, so I assume DataStores are in play. I could use:

--if (something) then
wait(7200)
--insert timer expiration notification or something

But how would I make sure that the timer keeps going even after the player leaves the game? Is there a service that I can use for this? I would appreciate any assistance, however obvious the answer might be.

1 answer

Log in to vote
1
Answered by 8 years ago
Edited 8 years ago

Difference

The trick to saving how much time has passed is not actually a timer in the background constantly changing, but instead it's just comparing two numbers and subtracting them. These two numbers that you're comparing is the time your event started, and the current time. Subtracting the current time by the initial start time, will give you the difference.

The only thing you need to save is the time in which the timer begins, and from that point forward you'll just be subtracting the starting time, from the current time.

Appropriate time stamp

It's also important to use the appropriate time stamp when saving this data. You really shouldn't use tick for a situation like this, as tick returns local time. Instead, you should use os.time, which returns a "global" time stamp that should be the same on all systems.

Implementation

Implementing this is pretty simple. For starters, obviously we'll save the time in which we want to start our counter off. So in this example, we'll just create a data store that saves that value to a key called "ServerTime", and we'll make the comparison as soon as the server starts.

-- Get the data store service
local datastore = game:GetService("DataStoreService")

-- Create a new data store
local data = datastore:GetDataStore("GameData")

-- Check for a key called "ServerTime", and if one doesn't exist, then set one.
local serverTime = data:GetAsync("ServerTime")

if serverTime == nil then
    data:SetAsync("ServerTime", os.time()) -- Set the initial time
else
    -- os.time() - serverTime will return how many seconds have passed
    local difference = os.time() - serverTime
    print(difference .. " seconds have passed")

    --If the amount of seconds is >= 60*5 seconds (or 5 minutes) then...
    if difference >= 60*5 then
        print("Time up!")
    end
end

Hope this helped, let me know if you have any questions.

0
Thanks for the help, it works great! I do have a question, though: How would I go about resetting the time? I'm not very good at DataStores (yet). DarkSideKyp 50 — 8y
Ad

Answer this question