Calculating Time Played

I would like to estimate how long someone has played my game. This is a bit tricky since apps can be placed in the background, or just idle waiting for player input.

I’m less worried about the idle, but would not like to count the app running in the background if possible. Is there any tips, tricks, or gotchas with calculating the play time?

You could just record the time that the session starts/resumes, and when it exits/suspends record the time again.The difference between the 2 values will be the time the game has played. If you need to keep a continuous count of how long they’ve played then just save that number, and every time a session occurs increment the saved value accordingly:

local startTime = 0 local endTime = 0 local thisSessionTime = 0 local allTimeSessionTime = 0 local function saveTime(newTime) allTimeSessionTime = loadThisFromAFile() allTimeSessionTime = allTimeSessionTime + newTime saveToTheFile(allTimeSessionTime) end local function onSystemEvent( event ) if event.type == "applicationStart" or event.type == "applicationResume" then startTime = os.time() elseif event.type == "applicationExit" or event.type == "applicationSuspend" then endTime = os.time() thisSessionTime = endTime - startTime saveTime(thisSessionTime) end end Runtime:addEventListener( "system", onSystemEvent )

Exactly what I was looking for - system events! Thanks!!

You could just record the time that the session starts/resumes, and when it exits/suspends record the time again.The difference between the 2 values will be the time the game has played. If you need to keep a continuous count of how long they’ve played then just save that number, and every time a session occurs increment the saved value accordingly:

local startTime = 0 local endTime = 0 local thisSessionTime = 0 local allTimeSessionTime = 0 local function saveTime(newTime) allTimeSessionTime = loadThisFromAFile() allTimeSessionTime = allTimeSessionTime + newTime saveToTheFile(allTimeSessionTime) end local function onSystemEvent( event ) if event.type == "applicationStart" or event.type == "applicationResume" then startTime = os.time() elseif event.type == "applicationExit" or event.type == "applicationSuspend" then endTime = os.time() thisSessionTime = endTime - startTime saveTime(thisSessionTime) end end Runtime:addEventListener( "system", onSystemEvent )

Exactly what I was looking for - system events! Thanks!!