WoWInterface - View Single Post - Code share: Perfect AFK Timer (CPU friendly with excellent accuracy)
View Single Post
09-17-15, 06:09 AM   #1
Nikita S. Doroshenko
A Cyclonian
Nikita S. Doroshenko's Avatar
AddOn Author - Click to view addons
Join Date: Sep 2015
Posts: 44
Code share: Perfect AFK Timer (CPU friendly with excellent accuracy)

Maybe for someone this code will be usefull. I share this AFK Timer, because most of timers that already exist and "detects" - AFK - works by "PLAYER_FLAGS_CHANGED" EVENT. But it's not correct, because game detect any mouse move and keypress and then it reset afk timer.

For example, if you will move your mouse every 29 minutes or press any key (i mean ANY, for example CTRL), you will never be kicked from game World, for AFK.

As well, most timers uses "OnUpdate" event that triggers every frame, and it's not CPU efficient.

This is very simple and very CPU friendly code, that detects logout (AFK) time with perfect precision.
This code uses only ticker instead of "OnUpdate", that's why it's very CPU friendly.

Even that C_Timer.NewTicker i think a bit more expensive then "OnUpdate", it triggers a lot more rarely.

Only thing it's not tracking - combat or out of combat. But i think it's easy to implement in future.

Lua Code:
  1. local function InitializeAdvancedGameTimer()
  2.     local step = 1
  3.     local x, y
  4.     local timer = 0
  5.     -- NEED TO ADD FEATURE (Disable timer in Combat)
  7.     local f  = Frame or CreateFrame("Frame", "Frame", UIParent)
  8.     local function PropagateKeyboardInput(self, key)
  10.         timer = 0
  11.     end
  12.     f:SetScript("OnKeyDown", PropagateKeyboardInput)
  13.     f:SetPropagateKeyboardInput(true)
  15.     local function GetMousePosition()
  16.         x, y = GetCursorPosition();
  17.     end
  18.     local function CheckMousePosition()
  19.         local nx, ny = GetCursorPosition();
  20.         if x ~= nx and y ~= ny then
  21.             x, y = GetCursorPosition();
  23.             timer = 0
  24.         else
  25.             timer = timer + step
  26.             if timer > 10 then
  27.                 print("LOGOUT IN "..YELLOW_FONT_COLOR_CODE..1800 - timer..FONT_COLOR_CODE_CLOSE.." SEC.")
  28.             end
  29.         end
  30.     end
  31.     GetMousePosition()
  32.     C_Timer.NewTicker(step, CheckMousePosition)
  33. end
  34. InitializeAdvancedGameTimer()

To make this code more CPU efficient, you can change step from 1 second to 10 for example.

P.S. Thank you MunkDev for helping with code that detects keypress - http://www.wowinterface.com/forums/s...ad.php?t=52723

Last edited by Nikita S. Doroshenko : 09-17-15 at 06:16 AM.
  Reply With Quote