util/watchdog.lua
author Kim Alvefur <zash@zash.se>
Fri, 21 Sep 2018 21:19:44 +0200
changeset 9339 9e8d7d461c7d
parent 8558 4f0f5b49bb03
child 12549 5059a639f61e
permissions -rw-r--r--
mod_http: Hook the host-less event if hooked from a global module

local timer = require "util.timer";
local setmetatable = setmetatable;
local os_time = os.time;

local _ENV = nil;
-- luacheck: std none

local watchdog_methods = {};
local watchdog_mt = { __index = watchdog_methods };

local function new(timeout, callback)
	local watchdog = setmetatable({ timeout = timeout, last_reset = os_time(), callback = callback }, watchdog_mt);
	timer.add_task(timeout+1, function (current_time)
		local last_reset = watchdog.last_reset;
		if not last_reset then
			return;
		end
		local time_left = (last_reset + timeout) - current_time;
		if time_left < 0 then
			return watchdog:callback();
		end
		return time_left + 1;
	end);
	return watchdog;
end

function watchdog_methods:reset()
	self.last_reset = os_time();
end

function watchdog_methods:cancel()
	self.last_reset = nil;
end

return {
	new = new;
};