Added util/timer.lua - a timer API
[prosody.git] / util / timer.lua
1 -- Prosody IM v0.3
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10 local ns_addtimer = require "net.server".addtimer;
11 local get_time = os.time;
12 local t_insert = table.insert;
13 local ipairs = ipairs;
14 local type = type;
15
16 local data = {};
17 local new_data = {};
18
19 module "timer"
20
21 local function _add_task(delay, func)
22         local current_time = get_time();
23         delay = delay + current_time;
24         if delay >= current_time then
25                 t_insert(new_data, {delay, func});
26         else func(); end
27 end
28
29 add_task = _add_task;
30
31 ns_addtimer(function()
32         local current_time = get_time();
33         for _, d in ipairs(new_data) do
34                 t_insert(data, d);
35         end
36         new_data = {};
37         for i = #data,1 do
38                 local t, func = data[i][1], data[i][2];
39                 if t <= current_time then
40                         data[i] = nil;
41                         local r = func();
42                         if type(r) == "number" then _add_task(r, func); end
43                 end
44         end
45 end);
46
47 return _M;