diff --git a/cron.lua b/cron.lua index 3f3a3f8..0ef5cb9 100644 --- a/cron.lua +++ b/cron.lua @@ -22,6 +22,7 @@ local function newEntry(time, callback, update, ...) update = update } entries[entry] = entry + return entry end local function updateTimedEntry(self, dt) @@ -32,6 +33,15 @@ local function updateTimedEntry(self, dt) 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 = {} @@ -41,13 +51,12 @@ end function cron.after(time, callback, ...) checkTimeAndCallback(time, callback) - return newEntry(time, callback, updateTimedEntry, ...) end function cron.every(time, callback, ...) checkTimeAndCallback(time, callback) - + return newEntry(time, callback, updatePeriodicEntry, ...) end function cron.update(dt) diff --git a/spec/cron_spec.lua b/spec/cron_spec.lua index 4664b92..6af5081 100644 --- a/spec/cron_spec.lua +++ b/spec/cron_spec.lua @@ -68,6 +68,18 @@ context( 'cron', function() assert_error(function() cron.every(-2, count) end) assert_not_error(function() cron.every(2, count) 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)