adds recurring timers

This commit is contained in:
Harald Albrecht 2019-02-08 18:14:05 +01:00
parent 5706552a3f
commit 2f18366c16
2 changed files with 38 additions and 2 deletions

View File

@ -34,7 +34,8 @@ Timer.__index = Timer
-- Cancels a timer, regardless of whether it has already been triggered, or
-- not.
function Timer:cancel()
if self.at >= 0 then
if self:isarmed() then
-- Don't forget to remove ourselves if we were still armed.
mb.timers:delete(self.at, self.timerf)
self.at = math.mininteger
end
@ -62,8 +63,8 @@ end
function mb.after(afterms, timerf, ...)
local at = mb.now + (afterms < 0 and 0 or afterms)
local tim = {
timerf = timerf,
at = at,
timerf = timerf,
targs = {...}
}
setmetatable(tim, Timer)
@ -71,6 +72,27 @@ function mb.after(afterms, timerf, ...)
return tim
end
-- Triggers a timer every specified ms until it finally gets canceled. Please
-- note that the trigger will trigger for the first time only after "everyms",
-- but not immediately.
function mb.every(everyms, timerf, ...)
local shim = {
everyms = everyms < 1 and 1 or everyms,
timerf = timerf,
targs = {...}
}
local tim = mb.after(
everyms,
function(shim)
shim.timerf(table.unpack(shim.targs))
shim.tim.at = mb.now + everyms
mb.timers:add(shim.tim.at, shim.tim)
end,
shim)
shim.tim = tim
return tim
end
-- Tick gets called by the Keybow "firmware" every 1ms (or so). If any timers
-- have gone off by now, then call their timer user functions. Keybow's tick
-- ms counter has its epoch set when the Keybow Lua scripting started (so it's

View File

@ -93,4 +93,18 @@ describe("multibow timers", function()
assert.spy(trigger).was_not.called()
end)
it("goes on, and on, and on...", function()
local trigger = spy.new(function() end)
local timer = mb.every(20, trigger, 1, 2, 3)
ticktock(50)
assert.spy(trigger).was.called(2)
assert.spy(trigger).was.called_with(1, 2, 3)
trigger:clear()
timer:cancel()
ticktock(50)
assert.spy(trigger).was_not.called()
end)
end)