Created
December 4, 2013 04:00
-
-
Save kenshinx/7782130 to your computer and use it in GitHub Desktop.
lua timer. based on luajit ffi load signal
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
--Lua timer library based on C signal. | |
--Notice: signal need Posfix system support | |
local ffi = require "ffi" | |
ffi.cdef[[ | |
typedef void (*sighandler_t) (int32_t); | |
extern sighandler_t signal (int32_t signum, sighandler_t handler); | |
unsigned int alarm(unsigned int seconds); | |
]] | |
local SIG_ERR = -1 | |
local SIGALRM = 14 | |
local SIG_CANCEL = 0 | |
local Timer = {} | |
function Timer.new(self,expire,callback, ...) | |
self.__index = self | |
self.expire = expire | |
self.callback = callback | |
self.args = {...} | |
return setmetatable({},self) | |
end | |
function Timer.start(self) | |
local trigger = function() self:call() end | |
local handler = ffi.C.signal(SIGALRM,trigger) | |
ffi.C.alarm(self.expire) | |
end | |
function Timer.cancel(self) | |
-- self.callback = nil | |
ffi.C.alarm(SIG_CANCEL) | |
end | |
function Timer.call(self) | |
if self.callback then | |
local ok = pcall(self.callback,unpack(self.args)) | |
if not ok then | |
error("fail execute timer callback.") | |
end | |
end | |
end | |
function Timer.timeout(self) | |
return os.time() > self.expired | |
end | |
local function sleep(n) | |
os.execute("sleep " .. tonumber(n)) | |
end | |
local callback = function(s) print(s) end | |
local timer = Timer:new(1,callback,"abc") | |
timer:start() | |
sleep(3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment