8bb1c11507b6e30615adc5ea450f3a4db9df76b9
[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 ipairs(new_data) do
36                         t_insert(data, d);
37                 end
38                 new_data = {};
39         elseif #data == 0 then
40                 return;
41         end
42         
43         for i, d in pairs(data) do
44                 local t, func = d[1], d[2];
45                 if t <= current_time then
46                         t_remove(data, i);
47                         local r = func();
48                         if type(r) == "number" then _add_task(r, func); end
49                 end
50         end
51 end);
52
53 return _M;