Skip to content

Commit

Permalink
fix(time): one timer will be canceled by another 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 28, 2023
1 parent cae528d commit c12de65
Showing 1 changed file with 15 additions and 22 deletions.
37 changes: 15 additions & 22 deletions time.lua
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,7 @@ local time = require 'eco.core.time'

local M = {}

local timers = {}
local timers_periodic = {}

local function new_timer(periodic)
local tmrs = periodic and timers_periodic or timers
for _, w in ipairs(tmrs) do
if not w:active() then
return w
end
end

local w = eco.watcher(eco.TIMER, periodic)

if #tmrs < 10 then
tmrs[#tmrs + 1] = w
end

return w
end
local sleep_timers = {}

-- returns the Unix time, the number of seconds elapsed since January 1, 1970 UTC.
function M.now()
Expand All @@ -35,7 +17,18 @@ end
A negative or zero delay causes sleep to return immediately.
--]]
function M.sleep(delay)
local w = new_timer()
for _, w in ipairs(sleep_timers) do
if not w:active() then
return w:wait(delay)
end
end

local w = eco.watcher(eco.TIMER)

if #sleep_timers < 10 then
sleep_timers[#sleep_timers + 1] = w
end

return w:wait(delay)
end

Expand Down Expand Up @@ -64,7 +57,7 @@ function M.timer(cb, ...)
assert(type(cb) == 'function')

return setmetatable({
w = new_timer(),
w = eco.watcher(eco.TIMER),
cb = cb,
arguments = { ... }
}, metatable)
Expand Down Expand Up @@ -95,7 +88,7 @@ function M.on(ts, cb, ...)
assert(type(cb) == 'function')

local tmr = setmetatable({
w = new_timer(true),
w = eco.watcher(eco.TIMER, true),
cb = cb,
arguments = { ... }
}, metatable)
Expand Down

0 comments on commit c12de65

Please sign in to comment.