Asa@0: --- **AceTimer-3.0** provides a central facility for registering timers. Asa@0: -- AceTimer supports one-shot timers and repeating timers. All timers are stored in an efficient Asa@0: -- data structure that allows easy dispatching and fast rescheduling. Timers can be registered, rescheduled Asa@0: -- or canceled at any time, even from within a running timer, without conflict or large overhead.\\ Asa@0: -- AceTimer is currently limited to firing timers at a frequency of 0.1s. This constant may change Asa@0: -- in the future, but for now it seemed like a good compromise in efficiency and accuracy. Asa@0: -- Asa@0: -- All `:Schedule` functions will return a handle to the current timer, which you will need to store if you Asa@0: -- need to cancel or reschedule the timer you just registered. Asa@0: -- Asa@0: -- **AceTimer-3.0** can be embeded into your addon, either explicitly by calling AceTimer:Embed(MyAddon) or by Asa@0: -- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object Asa@0: -- and can be accessed directly, without having to explicitly call AceTimer itself.\\ Asa@0: -- It is recommended to embed AceTimer, otherwise you'll have to specify a custom `self` on all calls you Asa@0: -- make into AceTimer. Asa@0: -- @class file Asa@0: -- @name AceTimer-3.0 Asa@0: -- @release $Id: AceTimer-3.0.lua 895 2009-12-06 16:28:55Z nevcairiel $ Asa@0: Asa@0: --[[ Asa@0: Basic assumptions: Asa@0: * In a typical system, we do more re-scheduling per second than there are timer pulses per second Asa@0: * Regardless of timer implementation, we cannot guarantee timely delivery due to FPS restriction (may be as low as 10) Asa@0: Asa@0: This implementation: Asa@0: CON: The smallest timer interval is constrained by HZ (currently 1/10s). Asa@0: PRO: It will still correctly fire any timer slower than HZ over a length of time, e.g. 0.11s interval -> 90 times over 10 seconds Asa@0: PRO: In lag bursts, the system simly skips missed timer intervals to decrease load Asa@0: CON: Algorithms depending on a timer firing "N times per minute" will fail Asa@0: PRO: (Re-)scheduling is O(1) with a VERY small constant. It's a simple linked list insertion in a hash bucket. Asa@0: CAUTION: The BUCKETS constant constrains how many timers can be efficiently handled. With too many hash collisions, performance will decrease. Asa@0: Asa@0: Major assumptions upheld: Asa@0: - ALLOWS scheduling multiple timers with the same funcref/method Asa@0: - ALLOWS scheduling more timers during OnUpdate processing Asa@0: - ALLOWS unscheduling ANY timer (including the current running one) at any time, including during OnUpdate processing Asa@0: ]] Asa@0: Asa@0: local MAJOR, MINOR = "AceTimer-3.0", 5 Asa@0: local AceTimer, oldminor = LibStub:NewLibrary(MAJOR, MINOR) Asa@0: Asa@0: if not AceTimer then return end -- No upgrade needed Asa@0: Asa@0: AceTimer.hash = AceTimer.hash or {} -- Array of [0..BUCKET-1] = linked list of timers (using .next member) Asa@0: -- Linked list gets around ACE-88 and ACE-90. Asa@0: AceTimer.selfs = AceTimer.selfs or {} -- Array of [self]={[handle]=timerobj, [handle2]=timerobj2, ...} Asa@0: AceTimer.frame = AceTimer.frame or CreateFrame("Frame", "AceTimer30Frame") Asa@0: Asa@0: -- Lua APIs Asa@0: local assert, error, loadstring = assert, error, loadstring Asa@0: local setmetatable, rawset, rawget = setmetatable, rawset, rawget Asa@0: local select, pairs, type, next, tostring = select, pairs, type, next, tostring Asa@0: local floor, max, min = math.floor, math.max, math.min Asa@0: local tconcat = table.concat Asa@0: Asa@0: -- WoW APIs Asa@0: local GetTime = GetTime Asa@0: Asa@0: -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded Asa@0: -- List them here for Mikk's FindGlobals script Asa@0: -- GLOBALS: DEFAULT_CHAT_FRAME, geterrorhandler Asa@0: Asa@0: -- Simple ONE-SHOT timer cache. Much more efficient than a full compost for our purposes. Asa@0: local timerCache = nil Asa@0: Asa@0: --[[ Asa@0: Timers will not be fired more often than HZ-1 times per second. Asa@0: Keep at intended speed PLUS ONE or we get bitten by floating point rounding errors (n.5 + 0.1 can be n.599999) Asa@0: If this is ever LOWERED, all existing timers need to be enforced to have a delay >= 1/HZ on lib upgrade. Asa@0: If this number is ever changed, all entries need to be rehashed on lib upgrade. Asa@0: ]] Asa@0: local HZ = 11 Asa@0: Asa@0: --[[ Asa@0: Prime for good distribution Asa@0: If this number is ever changed, all entries need to be rehashed on lib upgrade. Asa@0: ]] Asa@0: local BUCKETS = 131 Asa@0: Asa@0: local hash = AceTimer.hash Asa@0: for i=1,BUCKETS do Asa@0: hash[i] = hash[i] or false -- make it an integer-indexed array; it's faster than hashes Asa@0: end Asa@0: Asa@0: --[[ Asa@0: xpcall safecall implementation Asa@0: ]] Asa@0: local xpcall = xpcall Asa@0: Asa@0: local function errorhandler(err) Asa@0: return geterrorhandler()(err) Asa@0: end Asa@0: Asa@0: local function CreateDispatcher(argCount) Asa@0: local code = [[ Asa@0: local xpcall, eh = ... -- our arguments are received as unnamed values in "..." since we don't have a proper function declaration Asa@0: local method, ARGS Asa@0: local function call() return method(ARGS) end Asa@0: Asa@0: local function dispatch(func, ...) Asa@0: method = func Asa@0: if not method then return end Asa@0: ARGS = ... Asa@0: return xpcall(call, eh) Asa@0: end Asa@0: Asa@0: return dispatch Asa@0: ]] Asa@0: Asa@0: local ARGS = {} Asa@0: for i = 1, argCount do ARGS[i] = "arg"..i end Asa@0: code = code:gsub("ARGS", tconcat(ARGS, ", ")) Asa@0: return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler) Asa@0: end Asa@0: Asa@0: local Dispatchers = setmetatable({}, { Asa@0: __index=function(self, argCount) Asa@0: local dispatcher = CreateDispatcher(argCount) Asa@0: rawset(self, argCount, dispatcher) Asa@0: return dispatcher Asa@0: end Asa@0: }) Asa@0: Dispatchers[0] = function(func) Asa@0: return xpcall(func, errorhandler) Asa@0: end Asa@0: Asa@0: local function safecall(func, ...) Asa@0: return Dispatchers[select('#', ...)](func, ...) Asa@0: end Asa@0: Asa@0: local lastint = floor(GetTime() * HZ) Asa@0: Asa@0: -- -------------------------------------------------------------------- Asa@0: -- OnUpdate handler Asa@0: -- Asa@0: -- traverse buckets, always chasing "now", and fire timers that have expired Asa@0: Asa@0: local function OnUpdate() Asa@0: local now = GetTime() Asa@0: local nowint = floor(now * HZ) Asa@0: Asa@0: -- Have we passed into a new hash bucket? Asa@0: if nowint == lastint then return end Asa@0: Asa@0: local soon = now + 1 -- +1 is safe as long as 1 < HZ < BUCKETS/2 Asa@0: Asa@0: -- Pass through each bucket at most once Asa@0: -- Happens on e.g. instance loads, but COULD happen on high local load situations also Asa@0: for curint = (max(lastint, nowint - BUCKETS) + 1), nowint do -- loop until we catch up with "now", usually only 1 iteration Asa@0: local curbucket = (curint % BUCKETS)+1 Asa@0: -- Yank the list of timers out of the bucket and empty it. This allows reinsertion in the currently-processed bucket from callbacks. Asa@0: local nexttimer = hash[curbucket] Asa@0: hash[curbucket] = false -- false rather than nil to prevent the array from becoming a hash Asa@0: Asa@0: while nexttimer do Asa@0: local timer = nexttimer Asa@0: nexttimer = timer.next Asa@0: local when = timer.when Asa@0: Asa@0: if when < soon then Asa@0: -- Call the timer func, either as a method on given object, or a straight function ref Asa@0: local callback = timer.callback Asa@0: if type(callback) == "string" then Asa@0: safecall(timer.object[callback], timer.object, timer.arg) Asa@0: elseif callback then Asa@0: safecall(callback, timer.arg) Asa@0: else Asa@0: -- probably nilled out by CancelTimer Asa@0: timer.delay = nil -- don't reschedule it Asa@0: end Asa@0: Asa@0: local delay = timer.delay -- NOW make a local copy, can't do it earlier in case the timer cancelled itself in the callback Asa@0: Asa@0: if not delay then Asa@0: -- single-shot timer (or cancelled) Asa@0: AceTimer.selfs[timer.object][tostring(timer)] = nil Asa@0: timerCache = timer Asa@0: else Asa@0: -- repeating timer Asa@0: local newtime = when + delay Asa@0: if newtime < now then -- Keep lag from making us firing a timer unnecessarily. (Note that this still won't catch too-short-delay timers though.) Asa@0: newtime = now + delay Asa@0: end Asa@0: timer.when = newtime Asa@0: Asa@0: -- add next timer execution to the correct bucket Asa@0: local bucket = (floor(newtime * HZ) % BUCKETS) + 1 Asa@0: timer.next = hash[bucket] Asa@0: hash[bucket] = timer Asa@0: end Asa@0: else -- if when>=soon Asa@0: -- reinsert (yeah, somewhat expensive, but shouldn't be happening too often either due to hash distribution) Asa@0: timer.next = hash[curbucket] Asa@0: hash[curbucket] = timer Asa@0: end -- if whenhandle->timer registry Asa@0: local handle = tostring(timer) Asa@0: Asa@0: local selftimers = AceTimer.selfs[self] Asa@0: if not selftimers then Asa@0: selftimers = {} Asa@0: AceTimer.selfs[self] = selftimers Asa@0: end Asa@0: selftimers[handle] = timer Asa@0: selftimers.__ops = (selftimers.__ops or 0) + 1 Asa@0: Asa@0: return handle Asa@0: end Asa@0: Asa@0: --- Schedule a new one-shot timer. Asa@0: -- The timer will fire once in `delay` seconds, unless canceled before. Asa@0: -- @param callback Callback function for the timer pulse (funcref or method name). Asa@0: -- @param delay Delay for the timer, in seconds. Asa@0: -- @param arg An optional argument to be passed to the callback function. Asa@0: -- @usage Asa@0: -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("TimerTest", "AceTimer-3.0") Asa@0: -- Asa@0: -- function MyAddon:OnEnable() Asa@0: -- self:ScheduleTimer("TimerFeedback", 5) Asa@0: -- end Asa@0: -- Asa@0: -- function MyAddon:TimerFeedback() Asa@0: -- print("5 seconds passed") Asa@0: -- end Asa@0: function AceTimer:ScheduleTimer(callback, delay, arg) Asa@0: return Reg(self, callback, delay, arg) Asa@0: end Asa@0: Asa@0: --- Schedule a repeating timer. Asa@0: -- The timer will fire every `delay` seconds, until canceled. Asa@0: -- @param callback Callback function for the timer pulse (funcref or method name). Asa@0: -- @param delay Delay for the timer, in seconds. Asa@0: -- @param arg An optional argument to be passed to the callback function. Asa@0: -- @usage Asa@0: -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("TimerTest", "AceTimer-3.0") Asa@0: -- Asa@0: -- function MyAddon:OnEnable() Asa@0: -- self.timerCount = 0 Asa@0: -- self.testTimer = self:ScheduleRepeatingTimer("TimerFeedback", 5) Asa@0: -- end Asa@0: -- Asa@0: -- function MyAddon:TimerFeedback() Asa@0: -- self.timerCount = self.timerCount + 1 Asa@0: -- print(("%d seconds passed"):format(5 * self.timerCount)) Asa@0: -- -- run 30 seconds in total Asa@0: -- if self.timerCount == 6 then Asa@0: -- self:CancelTimer(self.testTimer) Asa@0: -- end Asa@0: -- end Asa@0: function AceTimer:ScheduleRepeatingTimer(callback, delay, arg) Asa@0: return Reg(self, callback, delay, arg, true) Asa@0: end Asa@0: Asa@0: --- Cancels a timer with the given handle, registered by the same addon object as used for `:ScheduleTimer` Asa@0: -- Both one-shot and repeating timers can be canceled with this function, as long as the `handle` is valid Asa@0: -- and the timer has not fired yet or was canceled before. Asa@0: -- @param handle The handle of the timer, as returned by `:ScheduleTimer` or `:ScheduleRepeatingTimer` Asa@0: -- @param silent If true, no error is raised if the timer handle is invalid (expired or already canceled) Asa@0: -- @return True if the timer was successfully cancelled. Asa@0: function AceTimer:CancelTimer(handle, silent) Asa@0: if not handle then return end -- nil handle -> bail out without erroring Asa@0: if type(handle) ~= "string" then Asa@0: error(MAJOR..": CancelTimer(handle): 'handle' - expected a string", 2) -- for now, anyway Asa@0: end Asa@0: local selftimers = AceTimer.selfs[self] Asa@0: local timer = selftimers and selftimers[handle] Asa@0: if silent then Asa@0: if timer then Asa@0: timer.callback = nil -- don't run it again Asa@0: timer.delay = nil -- if this is the currently-executing one: don't even reschedule Asa@0: -- The timer object is removed in the OnUpdate loop Asa@0: end Asa@0: return not not timer -- might return "true" even if we double-cancel. we'll live. Asa@0: else Asa@0: if not timer then Asa@0: geterrorhandler()(MAJOR..": CancelTimer(handle[, silent]): '"..tostring(handle).."' - no such timer registered") Asa@0: return false Asa@0: end Asa@0: if not timer.callback then Asa@0: geterrorhandler()(MAJOR..": CancelTimer(handle[, silent]): '"..tostring(handle).."' - timer already cancelled or expired") Asa@0: return false Asa@0: end Asa@0: timer.callback = nil -- don't run it again Asa@0: timer.delay = nil -- if this is the currently-executing one: don't even reschedule Asa@0: return true Asa@0: end Asa@0: end Asa@0: Asa@0: --- Cancels all timers registered to the current addon object ('self') Asa@0: function AceTimer:CancelAllTimers() Asa@0: if not(type(self) == "string" or type(self) == "table") then Asa@0: error(MAJOR..": CancelAllTimers(): 'self' - must be a string or a table",2) Asa@0: end Asa@0: if self == AceTimer then Asa@0: error(MAJOR..": CancelAllTimers(): supply a meaningful 'self'", 2) Asa@0: end Asa@0: Asa@0: local selftimers = AceTimer.selfs[self] Asa@0: if selftimers then Asa@0: for handle,v in pairs(selftimers) do Asa@0: if type(v) == "table" then -- avoid __ops, etc Asa@0: AceTimer.CancelTimer(self, handle, true) Asa@0: end Asa@0: end Asa@0: end Asa@0: end Asa@0: Asa@0: --- Returns the time left for a timer with the given handle, registered by the current addon object ('self'). Asa@0: -- This function will raise a warning when the handle is invalid, but not stop execution. Asa@0: -- @param handle The handle of the timer, as returned by `:ScheduleTimer` or `:ScheduleRepeatingTimer` Asa@0: -- @return The time left on the timer, or false if the handle is invalid. Asa@0: function AceTimer:TimeLeft(handle) Asa@0: if not handle then return end Asa@0: if type(handle) ~= "string" then Asa@0: error(MAJOR..": TimeLeft(handle): 'handle' - expected a string", 2) -- for now, anyway Asa@0: end Asa@0: local selftimers = AceTimer.selfs[self] Asa@0: local timer = selftimers and selftimers[handle] Asa@0: if not timer then Asa@0: geterrorhandler()(MAJOR..": TimeLeft(handle): '"..tostring(handle).."' - no such timer registered") Asa@0: return false Asa@0: end Asa@0: return timer.when - GetTime() Asa@0: end Asa@0: Asa@0: Asa@0: -- --------------------------------------------------------------------- Asa@0: -- PLAYER_REGEN_ENABLED: Run through our .selfs[] array step by step Asa@0: -- and clean it out - otherwise the table indices can grow indefinitely Asa@0: -- if an addon starts and stops a lot of timers. AceBucket does this! Asa@0: -- Asa@0: -- See ACE-94 and tests/AceTimer-3.0-ACE-94.lua Asa@0: Asa@0: local lastCleaned = nil Asa@0: Asa@0: local function OnEvent(this, event) Asa@0: if event~="PLAYER_REGEN_ENABLED" then Asa@0: return Asa@0: end Asa@0: Asa@0: -- Get the next 'self' to process Asa@0: local selfs = AceTimer.selfs Asa@0: local self = next(selfs, lastCleaned) Asa@0: if not self then Asa@0: self = next(selfs) Asa@0: end Asa@0: lastCleaned = self Asa@0: if not self then -- should only happen if .selfs[] is empty Asa@0: return Asa@0: end Asa@0: Asa@0: -- Time to clean it out? Asa@0: local list = selfs[self] Asa@0: if (list.__ops or 0) < 250 then -- 250 slosh indices = ~10KB wasted (max!). For one 'self'. Asa@0: return Asa@0: end Asa@0: Asa@0: -- Create a new table and copy all members over Asa@0: local newlist = {} Asa@0: local n=0 Asa@0: for k,v in pairs(list) do Asa@0: newlist[k] = v Asa@0: n=n+1 Asa@0: end Asa@0: newlist.__ops = 0 -- Reset operation count Asa@0: Asa@0: -- And since we now have a count of the number of live timers, check that it's reasonable. Emit a warning if not. Asa@0: if n>BUCKETS then Asa@0: DEFAULT_CHAT_FRAME:AddMessage(MAJOR..": Warning: The addon/module '"..tostring(self).."' has "..n.." live timers. Surely that's not intended?") Asa@0: end Asa@0: Asa@0: selfs[self] = newlist Asa@0: end Asa@0: Asa@0: -- --------------------------------------------------------------------- Asa@0: -- Embed handling Asa@0: Asa@0: AceTimer.embeds = AceTimer.embeds or {} Asa@0: Asa@0: local mixins = { Asa@0: "ScheduleTimer", "ScheduleRepeatingTimer", Asa@0: "CancelTimer", "CancelAllTimers", Asa@0: "TimeLeft" Asa@0: } Asa@0: Asa@0: function AceTimer:Embed(target) Asa@0: AceTimer.embeds[target] = true Asa@0: for _,v in pairs(mixins) do Asa@0: target[v] = AceTimer[v] Asa@0: end Asa@0: return target Asa@0: end Asa@0: Asa@0: -- AceTimer:OnEmbedDisable( target ) Asa@0: -- target (object) - target object that AceTimer is embedded in. Asa@0: -- Asa@0: -- cancel all timers registered for the object Asa@0: function AceTimer:OnEmbedDisable( target ) Asa@0: target:CancelAllTimers() Asa@0: end Asa@0: Asa@0: Asa@0: for addon in pairs(AceTimer.embeds) do Asa@0: AceTimer:Embed(addon) Asa@0: end Asa@0: Asa@0: -- --------------------------------------------------------------------- Asa@0: -- Debug tools (expose copies of internals to test suites) Asa@0: AceTimer.debug = AceTimer.debug or {} Asa@0: AceTimer.debug.HZ = HZ Asa@0: AceTimer.debug.BUCKETS = BUCKETS Asa@0: Asa@0: -- --------------------------------------------------------------------- Asa@0: -- Finishing touchups Asa@0: Asa@0: AceTimer.frame:SetScript("OnUpdate", OnUpdate) Asa@0: AceTimer.frame:SetScript("OnEvent", OnEvent) Asa@0: AceTimer.frame:RegisterEvent("PLAYER_REGEN_ENABLED") Asa@0: Asa@0: -- In theory, we should hide&show the frame based on there being timers or not. Asa@0: -- However, this job is fairly expensive, and the chance that there will Asa@0: -- actually be zero timers running is diminuitive to say the lest.