Skip to content

Commit

Permalink
perf(time): reduce memory usage of timer
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
  • Loading branch information
zhaojh329 committed Oct 8, 2023
1 parent 85f2ad5 commit 9131abd
Showing 1 changed file with 12 additions and 14 deletions.
26 changes: 12 additions & 14 deletions time.lua
Original file line number Diff line number Diff line change
Expand Up @@ -42,33 +42,32 @@ end
local timer_methods = {}

function timer_methods:cancel()
local mt = getmetatable(self)
mt.w:cancel()
self.w:cancel()
end

function timer_methods:set(delay)
local mt = getmetatable(self)
local w = mt.w
local w = self.w

w:cancel()

eco.run(function(...)
if w:wait(delay) then
mt.cb(...)
self.cb(...)
end
end, self, table.unpack(mt.arguments))
end, self, table.unpack(self.arguments))
end

local metatable = { __index = timer_methods }

-- The timer function is similar to `at`, but will not be started immediately.
function M.timer(cb, ...)
assert(type(cb) == 'function')

return setmetatable({}, {
return setmetatable({
w = new_timer(),
cb = cb,
arguments = { ... },
__index = timer_methods
})
arguments = { ... }
}, metatable)
end

--[[
Expand All @@ -95,12 +94,11 @@ function M.on(ts, cb, ...)
assert(type(ts) == 'number')
assert(type(cb) == 'function')

local tmr = setmetatable({}, {
local tmr = setmetatable({
w = new_timer(true),
cb = cb,
arguments = { ... },
__index = timer_methods
})
arguments = { ... }
}, metatable)

tmr:set(ts)

Expand Down

0 comments on commit 9131abd

Please sign in to comment.