Merged with main tip.
[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 t_remove = table.remove;
14 local ipairs, pairs = ipairs, pairs;
15 local type = type;
16
17 local data = {};
18 local new_data = {};
19
20 module "timer"
21
22 local function _add_task(delay, func)
23         local current_time = get_time();
24         delay = delay + current_time;
25         if delay >= current_time then
26                 t_insert(new_data, {delay, func});
27         else func(); end
28 end
29
30 add_task = _add_task;
31
32 ns_addtimer(function()
33         local current_time = get_time();
34         if #new_data > 0 then
35                 for _, d in pairs(new_data) do
36                         t_insert(data, d);
37                 end
38                 new_data = {};
39         end
40         
41         for i, d in pairs(data) do
42                 local t, func = d[1], d[2];
43                 if t <= current_time then
44                         data[i] = nil;
45                         local r = func();
46                         if type(r) == "number" then _add_task(r, func); end
47                 end
48         end
49 end);
50
51 return _M;