Created
March 18, 2013 18:16
-
-
Save mtourne/5189445 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local timer = { } | |
-- shared dictionary | |
local timer_queue = ngx.shared.timer_queue | |
local mt = { __index = timer } | |
local floor = math.floor | |
local ngx_now = ngx.now | |
local cmsgpack = require("cmsgpack") | |
local pack = cmsgpack.pack | |
local unpack = cmsgpack.unpack | |
local function get_curr_second(max_seconds) | |
return (floor(ngx_now()) % max_seconds) | |
end | |
local function get_timer_index(cur, seconds, max) | |
return ((cur + seconds) % max) + 1 | |
end | |
function timer.new(self, name, max_seconds_ahead) | |
local obj = { name = name, | |
max = max_seconds_ahead, | |
cur = get_curr_second(max_seconds_ahead), | |
} | |
for i = 1, max_seconds_ahead do | |
obj[i] = {} | |
end | |
return setmetatable(obj, mt) | |
end | |
function timer.load(self, name) | |
local packed = timer_queue:get(name) | |
if not packed then | |
return nil | |
end | |
local new_obj = unpack(packed) | |
new_obj.cur = get_curr_second(new_obj.max) | |
return setmetatable(new_obj, mt) | |
end | |
function timer.save(self) | |
return timer_queue:set(self.name, pack(self)) | |
end | |
function timer.once(self, in_secs, callback_string) | |
return table.insert(self[get_timer_index(self.cur, in_secs, self.max)], | |
callback_string) | |
end | |
function timer.exec_queued(self) | |
for _, callback_string in ipairs(self[self.cur + 1]) do | |
f = loadstring(callback_string) | |
f() | |
end | |
self[self.cur] = {} | |
end | |
-- safety net | |
local module_mt = { | |
__newindex = ( | |
function (table, key, val) | |
error('Attempt to write to undeclared variable "' .. key .. '"') | |
end), | |
} | |
setmetatable(timer, module_mt) | |
return timer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment