Aria Network

Description for util.timer from v3.10.x onward.

The timer API in Metronome allows to perform asynchronous time based operations by adding a callback to the server event loop which will fire when the timer expires, there’re several ways to use the timers library in Metronome’s code, you can require the library object by using:

require timer = “util.timer”;

Use the Module API, or require single API functions depending on what you need to do. We’ll begin by describing the single API functions exported by the library object:

  • timer.add_task(delay, callback[, origin, host]): add a task to the server loop, delay is the number in seconds, callback is a function to fire after the timer expired, origin is a string identifying the source of the timer, host is a string identifying the source host of the timer both origin and host are optional parameters. The callback gets passed one parameters being the EPOCH time in milliseconds. When ran add_task returns the UUID associated with the timer.
  • timer.remove_task(uuid): “removes” a timer from the server loop, by stopping it from firing the callback when the timer expires and calling libevent’s LEAVE event instead. Will return true when successful or false.
  • timer.remove_tasks_from_origin(origin, host): removes all tasks sourcing from the specified origin and host. Returns the number of entries removed.

All timers are otherwise enclosed into a simple dictionary called task_list exposed on the library object which entries contain delay, callback, origin and host and are indexed by the timer’s UUID. You can traverse the list using either pairs() or another custom iterator of your choice. Removing a task from this table will have the same effect as calling any of the removing API functions.

You can also create and remove tasks indirectly by using the Module API functions, this has the advantage to auto-flag the timers, and remove ’em when the module gets unloaded (or reloaded):

  • module:add_timer(delay, callback): calls add_task with specified delay and callback flagging it with the name of the module as origin and the module host as host.
  • module:remove_timer(uuid): simply map a call to remove task with the specified uuid.
  • module:remove_all_timers(): removes all timers from the current module.

And finally to repeat a timer you just need the callback to return a number with the time in seconds before recalling it again.