every is nearly working

This commit is contained in:
Enrique García Cota 2011-04-24 16:37:02 +02:00
parent 39cee89b94
commit e014cee5aa
2 changed files with 23 additions and 2 deletions

View File

@ -22,6 +22,7 @@ local function newEntry(time, callback, update, ...)
update = update update = update
} }
entries[entry] = entry entries[entry] = entry
return entry
end end
local function updateTimedEntry(self, dt) local function updateTimedEntry(self, dt)
@ -32,6 +33,15 @@ local function updateTimedEntry(self, dt)
end end
end end
local function updatePeriodicEntry(self, dt)
self.running = self.running + dt
if self.running >= self.time then
self.callback(unpack(self.args))
self.running=0
end
end
local cron = {} local cron = {}
@ -41,13 +51,12 @@ end
function cron.after(time, callback, ...) function cron.after(time, callback, ...)
checkTimeAndCallback(time, callback) checkTimeAndCallback(time, callback)
return newEntry(time, callback, updateTimedEntry, ...) return newEntry(time, callback, updateTimedEntry, ...)
end end
function cron.every(time, callback, ...) function cron.every(time, callback, ...)
checkTimeAndCallback(time, callback) checkTimeAndCallback(time, callback)
return newEntry(time, callback, updatePeriodicEntry, ...)
end end
function cron.update(dt) function cron.update(dt)

View File

@ -68,6 +68,18 @@ context( 'cron', function()
assert_error(function() cron.every(-2, count) end) assert_error(function() cron.every(-2, count) end)
assert_not_error(function() cron.every(2, count) end) assert_not_error(function() cron.every(2, count) end)
end) end)
test( 'Should execute periodical actions periodically', function()
cron.every(2, count)
cron.update(1)
assert_equal(counter, 0)
cron.update(1)
assert_equal(counter, 1)
cron.update(2)
assert_equal(counter, 2)
cron.update(1)
assert_equal(counter, 2)
end)
end) end)