Software /
code /
prosody
Comparison
util/watchdog.lua @ 12802:4a8740e01813
Merge 0.12->trunk
author | Kim Alvefur <zash@zash.se> |
---|---|
date | Mon, 12 Dec 2022 07:10:54 +0100 |
parent | 12547:e79c64b2dfed |
child | 12975:d10957394a3c |
comparison
equal
deleted
inserted
replaced
12801:ebd6b4d8bf04 | 12802:4a8740e01813 |
---|---|
1 local timer = require "util.timer"; | 1 local timer = require "util.timer"; |
2 local setmetatable = setmetatable; | 2 local setmetatable = setmetatable; |
3 local os_time = os.time; | |
4 | 3 |
5 local _ENV = nil; | 4 local _ENV = nil; |
6 -- luacheck: std none | 5 -- luacheck: std none |
7 | 6 |
8 local watchdog_methods = {}; | 7 local watchdog_methods = {}; |
9 local watchdog_mt = { __index = watchdog_methods }; | 8 local watchdog_mt = { __index = watchdog_methods }; |
10 | 9 |
11 local function new(timeout, callback) | 10 local function new(timeout, callback) |
12 local watchdog = setmetatable({ timeout = timeout, last_reset = os_time(), callback = callback }, watchdog_mt); | 11 local watchdog = setmetatable({ |
13 timer.add_task(timeout+1, function (current_time) | 12 timeout = timeout; |
14 local last_reset = watchdog.last_reset; | 13 callback = callback; |
15 if not last_reset then | 14 timer_id = nil; |
16 return; | 15 }, watchdog_mt); |
17 end | 16 |
18 local time_left = (last_reset + timeout) - current_time; | 17 watchdog:reset(); -- Kick things off |
19 if time_left < 0 then | 18 |
20 return watchdog:callback(); | |
21 end | |
22 return time_left + 1; | |
23 end); | |
24 return watchdog; | 19 return watchdog; |
25 end | 20 end |
26 | 21 |
27 function watchdog_methods:reset() | 22 function watchdog_methods:reset(new_timeout) |
28 self.last_reset = os_time(); | 23 if new_timeout then |
24 self.timeout = new_timeout; | |
25 end | |
26 if self.timer_id then | |
27 timer.reschedule(self.timer_id, self.timeout+1); | |
28 else | |
29 self.timer_id = timer.add_task(self.timeout+1, function () | |
30 return self:callback(); | |
31 end); | |
32 end | |
29 end | 33 end |
30 | 34 |
31 function watchdog_methods:cancel() | 35 function watchdog_methods:cancel() |
32 self.last_reset = nil; | 36 if self.timer_id then |
37 timer.stop(self.timer_id); | |
38 self.timer_id = nil; | |
39 end | |
33 end | 40 end |
34 | 41 |
35 return { | 42 return { |
36 new = new; | 43 new = new; |
37 }; | 44 }; |