Simple watchdog

I would like to share with you a simple watchdog that can be used for any go. It is written just for convenience, so if you’ll find it useful feel free to utilize it :wink: I was amazed by the usage of “:” instead of “.” that gives you a possibility to pass self object as a first argument. If you know the more professional word for upbeat, share it :smiley:

The watchdog.lua module could look like this:

local watchdog = {}
watchdog.__index = watchdog

function watchdog:create(delay, cb)
    assert(delay, "You must provide a delay")
    assert(cb, "You must provide a callback")
    assert(type(delay) == "number", "Delay must be a number")
    assert(type(cb) == "function", "Callback must be a function")
	self.delay = delay
	self.cb = cb
	self.timer = timer.delay(delay, false, cb)
end

function watchdog:upbeat(delay, cb)
    if delay then assert(type(delay) == "number", "Delay must be a number") end
    if cb then assert(type(cb) == "function", "Callback must be a function") end
	if self.timer then
		timer.cancel(self.timer)
		self.timer = timer.delay(delay or self.delay, false, cb or self.cb)
	end
end

return watchdog

Require it in your script:

local watchdog = require "main.watchdog"

And then create anywhere a timer, that you can easily upbeat and optionally change delay or a callback.

watchdog:create(3, function() print("3 sec passed") end)  -- after 3 seconds the text will be displayed

watchdog:upbeat()  -- upbeat a timer by its origin delay (3 sec), so now the text will be displayed after another 3 seconds (from the time the upbeat has been called)

watchdog:upbeat(4, function() print("4 sec passed") end) -- change delay or callback at will, so now a different text will be displayed after another 4 seconds

I’m using this for example to check if there is no more actions triggered that could cause my hero to attack, so he can hide his sword when it’s calm. Using watchdog to check, if there is a too long await for some action to happen (that would upbeat it) is its main purpose of course, so you can handle timeouts. If you have any ideas, that could improve this, feel free to share :wink:

9 Likes