When an application needs to trigger timers on a regular basis, perhaps to do some cleanup every minute or poll for changes, a simple timer could work, but has some disadvantages. Specifically, whatever code executes after the timer triggers but before its scheduled again takes time. Say you wait 60 seconds, then do 10 seconds of processing, then wait another 60 seconds, and so on. It would take 7 minutes to do 6 iterations, and may throw the whole system off. Or perhaps you'd like to update something every 5 seconds, but the update process may take 20-30 seconds, an advanced timer will tell you how many ticks of the timer have elapsed since you last acted on it.
To create a timer, call
local tfd = ratchet.timerfd.new()
Arm, Disarm, and Query
On creation, the timer is disarmed and will not tick. To arm the timer, pass
a non-zero floating-point number of seconds to
To query the time until the next timer tick, call
-- Arm the timer for 30 seconds from now, and keep resetting to 30 seconds. tfd:settime(30.0, 30.0) -- Do some processing... local time_left = tfd:gettime()
While querying the timer may be useful, the true power of advanced timers is in the monitoring ability. This allows the current thread to be paused until the next tick of the timer, or tell how many times the timer has ticked since the monitoring call.
To monitor an advanced timer, use the
-- Arm the timer for 5 seconds, and keep resetting to 5 seconds. tfd:settime(5.0, 5.0) -- Do 60 seconds of processing... local ticks = tfd:read() -- would return 12 right away tfd:read() -- pauses thread until next 5 second tick