util/watchdog.lua

changeset 0
d363a6692a10
equal deleted inserted replaced
-1:000000000000 0:d363a6692a10
1 local timer = require "util.timer";
2 local setmetatable = setmetatable;
3 local os_time = os.time;
4
5 module "watchdog"
6
7 local watchdog_methods = {};
8 local watchdog_mt = { __index = watchdog_methods };
9
10 function new(timeout, callback)
11 local watchdog = setmetatable({ timeout = timeout, last_reset = os_time(), callback = callback }, watchdog_mt);
12 timer.add_task(timeout+1, function (current_time)
13 local last_reset = watchdog.last_reset;
14 if not last_reset then
15 return;
16 end
17 local time_left = (last_reset + timeout) - current_time;
18 if time_left < 0 then
19 return watchdog:callback();
20 end
21 return time_left + 1;
22 end);
23 return watchdog;
24 end
25
26 function watchdog_methods:reset()
27 self.last_reset = os_time();
28 end
29
30 function watchdog_methods:cancel()
31 self.last_reset = nil;
32 end
33
34 return _M;

mercurial